diff --git a/docs/build/chain/concentrated-liquidity/README.md b/docs/build/chain/concentrated-liquidity/README.md index b694664a0..47604f73b 100644 --- a/docs/build/chain/concentrated-liquidity/README.md +++ b/docs/build/chain/concentrated-liquidity/README.md @@ -404,8 +404,8 @@ type MsgCreatePosition struct { UpperTick int64 TokenDesired0 types.Coin TokenDesired1 types.Coin - TokenMinAmount0 sdk.Int - TokenMinAmount1 sdk.Int + TokenMinAmount0 osmomath.Int + TokenMinAmount1 osmomath.Int } ``` @@ -417,10 +417,10 @@ create the liquidityCreated number of shares in the given range. ```go type MsgCreatePositionResponse struct { PositionId uint64 - Amount0 sdk.Int - Amount1 sdk.Int + Amount0 osmomath.Int + Amount1 osmomath.Int JoinTime time.Time - LiquidityCreated sdk.Dec + LiquidityCreated osmomath.Dec } ``` @@ -444,7 +444,7 @@ associated with the position are still retained until a user claims them manuall type MsgWithdrawPosition struct { PositionId uint64 Sender string - LiquidityAmount sdk.Dec + LiquidityAmount osmomath.Dec } ``` @@ -455,8 +455,8 @@ for the provided share liquidity amount. ```go type MsgWithdrawPositionResponse struct { - Amount0 sdk.Int - Amount1 sdk.Int + Amount0 osmomath.Int + Amount1 osmomath.Int } ``` @@ -478,7 +478,7 @@ type MsgCreateConcentratedPool struct { Denom0 string Denom1 string TickSpacing uint64 - SpreadFactor sdk.Dec + SpreadFactor osmomath.Dec } ``` @@ -530,10 +530,10 @@ the original join time so charging is preserved. type MsgAddToPosition struct { PositionId uint64 Sender string - Amount0 sdk.Int - Amount1 sdk.Int - TokenMinAmount0 sdk.Int - TokenMinAmount1 sdk.Int + Amount0 osmomath.Int + Amount1 osmomath.Int + TokenMinAmount0 osmomath.Int + TokenMinAmount1 osmomath.Int } ``` @@ -676,7 +676,7 @@ and token1 as a result the one that had higher liquidity will end up smaller than originally given by the user. Note that the liquidity used here does not represent an amount of a specific -token, but the liquidity of the pool itself, represented in `sdk.Dec`. +token, but the liquidity of the pool itself, represented in `osmomath.Dec`. Using the provided liquidity, now we calculate the delta amount of both token0 and token1, using the following equations, where L is the liquidity calculated above: @@ -695,9 +695,6 @@ Given the parameters needed for calculating the tokens needed for creating a position for a given tick, the API in the keeper layer would look like the following: ```go -ctx sdk.Context, poolId uint64, owner sdk.AccAddress, amount0Desired, -amount1Desired, amount0Min, amount1Min sdk.Int, -lowerTick, upperTick int64, frozenUntil time.Time func createPosition( ctx sdk.Context, poolId uint64, @@ -705,9 +702,9 @@ func createPosition( amount0Desired, amount1Desired, amount0Min, - amount1Min sdk.Int + amount1Min osmomath.Int, lowerTick, - upperTick int64) (amount0, amount1 sdk.Int, sdk.Dec, error) { + upperTick int64) (amount0, amount1 osmomath.Int, liquidity osmomath.Dec, err error) { ... } ``` @@ -730,9 +727,8 @@ func (k Keeper) withdrawPosition( owner sdk.AccAddress, lowerTick, upperTick int64, - frozenUntil time.Time, - requestedLiquidityAmountToWithdraw sdk.Dec) - (amtDenom0, amtDenom1 sdk.Int, err error) { + requestedLiquidityAmountToWithdraw osmomath.Dec) + (amtDenom0, amtDenom1 osmomath.Int, err error) { ... } ``` @@ -788,8 +784,8 @@ From the user perspective, there are two ways to swap: Each case has a corresponding message discussed previously in the `x/poolmanager` section. -- `MsgSwapExactIn` -- `MsgSwapExactOut` +- `MsgSwapExactAmountIn` +- `MsgSwapExactAmountOut` Once a message is received by the `x/poolmanager`, it is propagated into a corresponding keeper @@ -856,32 +852,32 @@ type SwapState struct { // if in given out, amount of token being swapped out. // Initialized to the amount of the token specified by the user. // Updated after every swap step. - amountSpecifiedRemaining sdk.Dec + amountSpecifiedRemaining osmomath.Dec // Amount of the other token that is calculated from the specified token. // if out given in, amount of token swapped out. // if in given out, amount of token swapped in. // Initialized to zero. // Updated after every swap step. - amountCalculated sdk.Dec + amountCalculated osmomath.Dec // Current sqrt price while calculating swap. // Initialized to the pool's current sqrt price. // Updated after every swap step. - sqrtPrice sdk.Dec + sqrtPrice osmomath.BigDec // Current tick while calculating swap. // Initialized to the pool's current tick. // Updated each time a tick is crossed. - tick sdk.Int + tick int64 // Current liqudiity within the active tick. // Initialized to the pool's current tick's liquidity. // Updated each time a tick is crossed. - liquidity sdk.Dec + liquidity osmomath.Dec // Global spread reward growth per-current swap. // Initialized to zero. // Updated after every swap step. - spreadRewardGrowthGlobal sdk.Dec + spreadRewardGrowthGlobal osmomath.Dec } ``` @@ -1164,15 +1160,6 @@ tick tracked by the pool is 11_000. The global spread reward growth per unit of has increased by 50 units of token one. See more details about the spread reward growth in the "Spread Rewards" section. -TODO: Swapping, Appendix B: Compute Swap Step Internals and Math - -## Range Orders - -> As a trader, I want to be able to execute ranger orders so that I have better -> control of the price at which I trade - -TODO - ## Spread Rewards > As a an LP, I want to earn spread rewards on my capital so that I am incentivized to @@ -1197,7 +1184,7 @@ layers of state: // Note that this is proto-generated. type Pool struct { ... - SpreadFactor sdk.Dec + SpreadFactor osmomath.Dec } ``` @@ -1460,7 +1447,7 @@ some [clever accumulator tricks](https://www.paradigm.xyz/2021/05/liquidity-mini this can be designed to ensure that each LP only receives incentives for liquidity they contribute to the active tick. This approach is incredible for liquidity depth, which is arguably the most important property we need incentives to be able to accommodate. It is also a user flow that -on-chain market makers are already somewhat familiar with and has enough live examples where +onchain market makers are already somewhat familiar with and has enough live examples where we roughly know that it functions as intended. ## Our Implementation @@ -1735,7 +1722,7 @@ the quote asset that has precision of 6 (e.g `uosmo` or `uusdc`). The true price of PEPE in USDC terms is `0.0000009749`. -In the "on-chain representation", this would be: +In the "onchain representation", this would be: `0.0000009749 * 10**6 / 10**18 = 9.749e-19` Note that this is below the minimum precision of `sdk.Dec`. diff --git a/docs/build/chain/cosmwasmpool/README.md b/docs/build/chain/cosmwasmpool/README.md index ba18417bd..88e170d16 100644 --- a/docs/build/chain/cosmwasmpool/README.md +++ b/docs/build/chain/cosmwasmpool/README.md @@ -9,8 +9,9 @@ The module is built on top of the CosmWasm smart contracting platform, which pro Having pools in CosmWasm provides several benefits, one of which is avoiding the need for chain upgrades when introducing new functionalities or modifying existing ones related to liquidity pools. This advantage is particularly important in the context of speed of development and iteration. -An example of a CosmWasm pool type: -- [transmuter](https://github.com/osmosis-labs/transmuter) +Examples of CosmWasm pool types: +- [transmuter](https://github.com/osmosis-labs/transmuter) (the constant-sum pools behind alloyed assets) +- [orderbook](https://github.com/osmosis-labs/orderbook) (the SumTree-based onchain orderbook markets) ## Key Components @@ -46,7 +47,7 @@ To create new CosmWasm Pool, there are 3 modules involved: `x/cosmwasmpool`, `x/ graph TD; Sender((Sender)) - Sender -- create poool --> x/cosmwasmpool + Sender -- create pool --> x/cosmwasmpool x/cosmwasmpool -- get next & set pool id --> x/poolmanager x/cosmwasmpool -- instantiate contract --> x/wasm ``` @@ -304,7 +305,7 @@ Ok(Response::new() ```rs #[cw_serde] pub struct AfterPoolCreated { - pub create_pool_guages: Option, + pub create_pool_gauges: Option, } #[cw_serde] @@ -387,7 +388,7 @@ Note, that in both cases, x/cosmwasmpool module account will act as the admin an Proposal Name: `UploadCosmWasmPoolCodeAndWhiteListProposal` On successful passing of this proposal, the code id of the pool contract will be added to the whitelist. -As a result, anyone would be able to instantiate a pool contract with this code id when creating a pol. +As a result, anyone would be able to instantiate a pool contract with this code id when creating a pool. No address will be able to maliciously upload a new code id and instantiate a pool contract with it without governance approval. @@ -413,7 +414,7 @@ In both cases, if one of the pools specified by the given `poolID` does not exis The reason for having `poolID`s be a slice of ids is to account for the potential need for emergency migration of all old code ids to new code ids, or simply having the flexibility of migrating multiple older pool contracts to a new one at once when there is a release. -`poolD`s must be at the most size of `PoolMigrationLimit` module parameter. It is configured to 20 at launch. +`poolID`s must be at the most size of `PoolMigrationLimit` module parameter. It is configured to 20 at launch. The proposal fails if more. Note that 20 was chosen arbitrarily to have a constant bound on the number of pools migrated at once. Inputs diff --git a/docs/build/chain/downtime-detector/README.md b/docs/build/chain/downtime-detector/README.md index 4135290b4..3297fb288 100644 --- a/docs/build/chain/downtime-detector/README.md +++ b/docs/build/chain/downtime-detector/README.md @@ -3,7 +3,8 @@ For several use cases, we need a module that can detect when the chain is recovering from downtime. We want to be able to efficiently know "Has it been `RECOVERY_PERIOD` minutes since the chain has been down for `DOWNTIME_PERIOD`", and expose this as a query to contracts. So for instance, you'd want to know if it has been at least 10 minutes, since the chain was down for > 30 minutes. Since you assume in such an event that it may take ~10 minutes for price oracles to be arb'd to correct. -Suggested Design + +## Suggested Design There's a couple designs, such as: @@ -15,7 +16,7 @@ There's a couple designs, such as: Because this will be in important txs for contracts, we need to go with the approach that has minimal query compute, which is the latter. So we explain that in more depth. -We restrict the `DOWNTIME_PERIOD` options that you can query, to be: 30seconds, 1 min, 2 min, 3 min, 4 min, 5 min, 10 min, 20 min, 30 min, 40 min, 50 min, 1 hr, 1.5hr, 2 hr, 2.5 hr, 3 hr, 4 hr, 5 hr, 6 hr, 9hr, 12hr, 18hr, 24hr, 36hr, 48hr. +We restrict the `DOWNTIME_PERIOD` options that you can query, to be: 30 seconds, 1 min, 2 min, 3 min, 4 min, 5 min, 10 min, 20 min, 30 min, 40 min, 50 min, 1 hr, 1.5 hr, 2 hr, 2.5 hr, 3 hr, 4 hr, 5 hr, 6 hr, 9 hr, 12 hr, 18 hr, 24 hr, 36 hr, 48 hr. In the downtime detector module, we store state entries for: @@ -27,4 +28,16 @@ Then in every begin block: * Store last blocks timestamp * if time since last block timestamp >= 30 seconds, iterate through all `DOWNTIME_PERIODS` less than the downtime, and in each add a state entry for the current block time -Then our query for has it been `RECOVERY_PERIOD` since `DOWNTIME_PERIOD`, simply reads the state entry for that `DOWNTIME_PERIOD`, and then checks if time difference between now and that block is > `RECOVERY_PERIOD`. \ No newline at end of file +Then our query for has it been `RECOVERY_PERIOD` since `DOWNTIME_PERIOD`, simply reads the state entry for that `DOWNTIME_PERIOD`, and then checks if time difference between now and that block is > `RECOVERY_PERIOD`. + +## Queries + +The module exposes a single gRPC query, `RecoveredSinceDowntimeOfLength`: + +* Request `RecoveredSinceDowntimeOfLengthRequest` + * `downtime` (`Downtime`): the downtime period to check, one of the restricted `DOWNTIME_PERIOD` options listed above (30 seconds through 48 hr), encoded as the `Downtime` enum (`DURATION_30S`, `DURATION_1M`, ... `DURATION_48H`). + * `recovery` (`google.protobuf.Duration`): the `RECOVERY_PERIOD` to check against. +* Response `RecoveredSinceDowntimeOfLengthResponse` + * `succesfully_recovered` (`bool`): true if it has been at least `recovery` since the last downtime of length `downtime`. (The misspelling is part of the deployed proto field name.) + +Source: [`proto/osmosis/downtimedetector/v1beta1/query.proto`](https://github.com/osmosis-labs/osmosis/blob/main/proto/osmosis/downtimedetector/v1beta1/query.proto) and [`downtime_duration.proto`](https://github.com/osmosis-labs/osmosis/blob/main/proto/osmosis/downtimedetector/v1beta1/downtime_duration.proto). \ No newline at end of file diff --git a/docs/build/chain/epochs/README.md b/docs/build/chain/epochs/README.md index c74612f05..b0da8dd72 100644 --- a/docs/build/chain/epochs/README.md +++ b/docs/build/chain/epochs/README.md @@ -20,7 +20,7 @@ they can easily be signalled upon such events. ## Concepts -The epochs module defines on-chain timers, that execute at fixed time intervals. +The epochs module defines onchain timers, that execute at fixed time intervals. Other SDK modules can then register logic to be executed at the timer ticks. We refer to the period in between two timer ticks as an "epoch". diff --git a/docs/build/chain/gamm/README.md b/docs/build/chain/gamm/README.md index d71d94635..6904ca3aa 100644 --- a/docs/build/chain/gamm/README.md +++ b/docs/build/chain/gamm/README.md @@ -36,7 +36,7 @@ us safe when it comes to the malicious creation of unneeded pools. #### Joining Pool -When joining a pool without swapping - with `JoinPool`, a user can provide the maximum amount of tokens `TokenInMaxs' +When joining a pool without swapping - with `JoinPool`, a user can provide the maximum amount of tokens `TokenInMaxs` they're willing to deposit. This argument must contain all the denominations from the pool or no tokens at all, otherwise, the tx will be aborted. If `TokenInMaxs` contains no tokens, the calculations are done based on the user's balance as the only constraint. @@ -165,7 +165,7 @@ Pools have the following parameters: | FutureGovernor | \*FutureGovernor | | Weights | \*Weights | | SmoothWeightChangeParams | \*SmoothWeightChangeParams | -| PoolCreationFee | sdk.Coins | +| PoolCreationFee (deprecated, see x/poolmanager `pool_creation_fee`) | sdk.Coins | 1. **SwapFee** - The swap fee is the cut of all swaps that goes to the Liquidity Providers (LPs) for a pool. Suppose a pool has a swap fee `s`. Then if a user wants to swap `T` tokens in the pool, `sT` tokens go to the LP's, and then `(1 - s)T` tokens are swapped according to the AMM swap function. @@ -182,7 +182,7 @@ Pools have the following parameters: This allows pool governance to smoothly change the weights of the assets it holds in the pool. So it can slowly move from a 2:1 ratio, to a 1:1 ratio. Currently, smooth weight changes are implemented as a linear change in weight ratios over a given duration of time. So weights changed from 4:1 to 2:2 over 2 days, then at day 1 of the change, the weights would be 3:1.5, and at day 2 its 2:2, and will remain at these weight ratios. -The GAMM module also has a **PoolCreationFee** parameter, which currently is set to `20000000 uusdc` or `20 USDC`. +The pool creation fee is governed by the `poolmanager` module's `pool_creation_fee` parameter, which is authoritative for pool creation across all pool types. The legacy `gamm` `PoolCreationFee` parameter is obsolete. Query the current value with `osmosisd query poolmanager params` rather than relying on a hardcoded figure. [comment]: `<>` (TODO Add better description of how the weights affect things) @@ -229,15 +229,15 @@ in `x/poolmanager` instead. Joins a pool by supplying a single asset; the module internally swaps part of it to match the pool's weights. -#### MsgJoinSwapShareAmountOut +### MsgJoinSwapShareAmountOut Joins a pool with a single asset such that the pool mints an exact number of shares to the joiner. -#### MsgExitSwapShareAmountIn +### MsgExitSwapShareAmountIn Burns an exact number of pool shares and withdraws the proceeds entirely in a single chosen asset. -#### MsgExitSwapExternAmountOut +### MsgExitSwapExternAmountOut Withdraws an exact amount of a single asset from a pool, burning as many shares as required. @@ -286,7 +286,7 @@ The configuration json file contains the following parameters: :::warning -There is now a 20 USDC fee for creating pools. +Creating a pool requires paying the pool creation fee. This fee is set by the `poolmanager` module's `pool_creation_fee` parameter (not `gamm`); query the current value with `osmosisd query poolmanager params`. ::: ### Join pool @@ -507,17 +507,25 @@ Query the number of active pools. osmosisd query gamm num-pools ``` -## Pool +#### Example + +Query the number of active pools. + +```sh +osmosisd query gamm num-pools +``` + +### Pool Query the parameter and assets of a specific pool. -### Usage +#### Usage ```sh osmosisd query gamm pool [flags] ``` -### Example +#### Example Query parameters and assets from pool 1. @@ -567,6 +575,30 @@ Query parameters and assets of all active pools. #### Usage +```sh +osmosisd query gamm pools +``` + +#### Example + +Query parameters and assets of all active pools. + +```sh +osmosisd query gamm pools +``` + +### Spot Price + +Query the spot price of a pool. Note that this command is legacy; the canonical spot-price query lives in `x/poolmanager`. + +#### Usage + +```sh +osmosisd query gamm spot-price [flags] +``` + +#### Example + Query the price of OSMO based on the price of ATOM in pool 1. ```sh @@ -630,11 +662,11 @@ It consists of the following attributes: * `sdk.AttributeKeyModule` - "module" * The value is the module's name - "gamm". * `sdk.AttributeKeySender` - * The value is the address of the sender who created the swap message. + * The value is the address of the sender who joined the pool. * `types.AttributeKeyPoolId` - * The value is the pool id of the pool where swap occurs. + * The value is the pool id of the pool that was joined. * `types.AttributeKeyTokensIn` - * The value is the string representation of the tokens being swapped in. + * The value is the string representation of the tokens deposited into the pool. ### `types.TypeEvtPoolExited` @@ -646,11 +678,11 @@ It consists of the following attributes: * `sdk.AttributeKeyModule` - "module" * The value is the module's name - "gamm". * `sdk.AttributeKeySender` - * The value is the address of the sender who created the swap message. + * The value is the address of the sender who exited the pool. * `types.AttributeKeyPoolId` - * The value is the pool id of the pool where swap occurs. + * The value is the pool id of the pool that was exited. * `types.AttributeKeyTokensOut` - * The value is the string representation of the tokens being swapped out. + * The value is the string representation of the tokens withdrawn from the pool. ### `types.TypeEvtPoolCreated` diff --git a/docs/build/chain/gamm/client/docs/README.md b/docs/build/chain/gamm/client/docs/README.md index c9587bdf6..cf9b14379 100644 --- a/docs/build/chain/gamm/client/docs/README.md +++ b/docs/build/chain/gamm/client/docs/README.md @@ -1,6 +1,6 @@ # CLI docs -TODO add an index here explaining each tx type +Available pool-creation CLI commands: -- [`create-pool`](./create-pool.md) -- [`create-lbp-pool`](./create-lbp-pool.md) +- [`create-pool`](./create-pool.md): create a balancer (weighted) liquidity pool from a JSON pool file defining the asset weights and initial reserves. +- [`create-lbp-pool`](./create-lbp-pool.md): create a liquidity bootstrapping pool whose weights shift linearly from the initial weights to the target weights over a set duration. diff --git a/docs/build/chain/gamm/pool-models/stableswap/README.md b/docs/build/chain/gamm/pool-models/stableswap/README.md index 6ec977311..5d5f1abe1 100644 --- a/docs/build/chain/gamm/pool-models/stableswap/README.md +++ b/docs/build/chain/gamm/pool-models/stableswap/README.md @@ -11,7 +11,7 @@ It is generalized to the multi-asset setting as $$f(a_1, ..., a_n) = a_1 * ... * ## Pool configuration -One key concept, is that the pool has a native concept of +One key concept is that the pool has a native concept of a scaling factor per asset, used to map raw coin units to AMM math units (detailed below). ### Scaling factor handling @@ -384,12 +384,11 @@ From this, we then derive what we'd expect for `JoinPool`. #### JoinPoolNoSwap and ExitPool -Both of these methods can be implemented via generic AMM techniques. -(Link to them or describe the idea) +Both of these methods can be implemented via generic AMM techniques: liquidity is added or removed in proportion to the existing reserves, so the ratio of reserves (and therefore the CFMM invariant up to scale) is preserved and no swap occurs. #### JoinPool -The JoinPool API only supports JoinPoolNoSwap if +The JoinPool API falls back to JoinPoolNoSwap when the provided tokens are already in the pool's reserve ratio, so that no swap is needed. Otherwise it is decomposed into a JoinPoolNoSwap on the in-ratio portion of the input, followed by a single-asset join (see below) on the remainder. #### Join pool single asset in diff --git a/docs/build/chain/gov/README.md b/docs/build/chain/gov/README.md index 8da2828df..1153713b4 100644 --- a/docs/build/chain/gov/README.md +++ b/docs/build/chain/gov/README.md @@ -1,6 +1,6 @@ # Gov -The `gov` module enables on-chain governance which allows Osmosis token holders to participate in a community led decision-making process. For example, users can: +The `gov` module enables onchain governance which allows Osmosis token holders to participate in a community led decision-making process. For example, users can: - Form an idea and seek feedback - Create a proposal and adjust according to feedback as needed @@ -74,18 +74,18 @@ typical flags would be: - `--gas=auto --gas-prices 0.05uosmo --gas-adjustment 1.3` to auto-calculate gas required. The `--gas-prices` value is illustrative: Osmosis sets a dynamic minimum gas price via its [fee market](/learn/features/fee-market), so query the current base fee (`osmosisd query txfees base-fee`) and pass a value at or above it. - `--from WALLET_ADDRESS` to set the running wallet -- `--deposit=400000000uosmo` to provide the initial 400 OSMO (25% of total) deposit for putting a proposal on chain +- `--deposit=1500000000uosmo` to provide the initial 1500 OSMO (25% of the `min_deposit`) deposit for putting a proposal on chain There are different types of proposal submission types, including -- [`text`](https://docs.osmosis.zone/osmosis-core/modules/gov#submit-proposal-text) -- [`param-change`](https://docs.osmosis.zone/osmosis-core/modules/gov#submit-proposal-param-change) -- [`community-pool-spend`](https://docs.osmosis.zone/osmosis-core/modules/gov#submit-proposal-community-pool-spend) -- [`software-upgrade`](https://docs.osmosis.zone/osmosis-core/modules/gov#submit-proposal-software-upgrade) and [`cancel-software-upgrade`](https://docs.osmosis.zone/osmosis-core/modules/gov#submit-proposal-cancel-software-upgrade) -- [`update-pool-incentives`](https://docs.osmosis.zone/osmosis-core/modules/gov#submit-proposal-update-pool-incentives) -- [`set-superfluid-asset`](https://docs.osmosis.zone/osmosis-core/modules/gov#submit-proposal-set-superfluid-asset) and [`remove-superfluid-asset`](https://docs.osmosis.zone/osmosis-core/modules/gov#submit-proposal-community-pool-spend) -- [`wasm-store`](https://docs.osmosis.zone/osmosis-core/modules/gov#submit-proposal-wasm-store) -- [`update-unpool-whitelist`](https://docs.osmosis.zone/osmosis-core/modules/gov#submit-proposal-update-unpool-whitelist) +- [`text`](#submit-proposal-text) +- [`param-change`](#submit-proposal-param-change) +- [`community-pool-spend`](#submit-proposal-community-pool-spend) +- [`software-upgrade`](#submit-proposal-software-upgrade) and [`cancel-software-upgrade`](#submit-proposal-cancel-upgrade) +- [`update-pool-incentives`](#submit-proposal-update-pool-incentives) +- [`set-superfluid-asset`](#submit-proposal-set-superfluid-asset) and [`remove-superfluid-asset`](#submit-proposal-remove-superfluid-asset) +- [`wasm-store`](#submit-proposal-wasm-store) +- [`update-unpool-whitelist`](#submit-proposal-update-unpool-whitelist) We will go over each of these submission types in detail now: @@ -94,7 +94,7 @@ We will go over each of these submission types in detail now: Text proposals differ from other proposal submission types in that after it passes, no logic is automatically executed. This is good for proposing changes to Osmosis that are not linked to a specific daemon parameter. ```bash -osmosisd tx gov submit-proposal --type=text --title="" --description="" --from WALLET_ADDRESS --deposit=400000000uosmo [flags] +osmosisd tx gov submit-proposal --type=text --title="" --description="" --from WALLET_ADDRESS --deposit=1500000000uosmo [flags] ``` **Example** @@ -102,7 +102,7 @@ osmosisd tx gov submit-proposal --type=text --title="" --description="" --from W Create a text signaling proposals to match external incentives for a `DOGE/OSMO` and `DOGE/ATOM` pair. ```bash -osmosisd tx gov submit-proposal --type=text --title="Match External Incentives for DOGE/OSMO and DOGE/ATOM pairs" --description="Input description" --from WALLET_ADDRESS --deposit=400000000uosmo --gas=auto --gas-prices 0.05uosmo --gas-adjustment 1.3 +osmosisd tx gov submit-proposal --type=text --title="Match External Incentives for DOGE/OSMO and DOGE/ATOM pairs" --description="Input description" --from WALLET_ADDRESS --deposit=1500000000uosmo --gas=auto --gas-prices 0.05uosmo --gas-adjustment 1.3 ``` ### submit-proposal (param change) @@ -134,7 +134,7 @@ The proposal.json file would look as follows: "value": 150 } ], - "deposit": "400000000uosmo" + "deposit": "1500000000uosmo" } ``` @@ -162,7 +162,7 @@ The proposal.json would look as follows: "description": "Establish a DAO for Osmosis. Potentially add external links for more information or allow discussion", "recipient": "osmo1r9pjvsuahxwkxg8cnhacd6alkmxq330fl9pqqt", "amount": "10000000000uosmo", - "deposit": "400000000uosmo" + "deposit": "1500000000uosmo" } ``` @@ -451,14 +451,14 @@ Which outputs: "min_deposit": [ { "denom": "uosmo", - "amount": "1600000000" + "amount": "6000000000" } ], "max_deposit_period": "1209600000000000", "min_expedited_deposit": [ { "denom": "uosmo", - "amount": "5000000000" + "amount": "20000000000" } ], "min_initial_deposit_ratio": "0.250000000000000000" @@ -482,7 +482,7 @@ The following tables show overall effects on different configurations of the `go | Higher | More collateral required to bring a proposal to vote | More time to solicit funds to reach `min_deposit` | Longer voting period | | Lower | Less collateral required to bring a proposal to vote | Less time to solicit funds to reach `min_deposit` | Shorter voting period | | Constraints | Value has to be a positive integer | Value has to be positive | Value has to be positive | -| Current configuration | `1600000000` (1600 OSMO) | `1209600000000000` (2 weeks) | `432000000000000` (5 days) | +| Current configuration | `6000000000` (6000 OSMO) | `1209600000000000` (2 weeks) | `432000000000000` (5 days) | | | `quorum` | `threshold` | `veto` | | --------------------- | ------------------------------------ | ------------------------------------ | ------------------------------------ | @@ -494,8 +494,8 @@ The following tables show overall effects on different configurations of the `go | | `min_expedited_deposit` | `expedited_threshold` | `expedited_voting_period` | | --------------------- | --------------------------------------------------------------- | --------------------------------------------- | ------------------------------- | -| Type | string (time ns) | string (dec) | string (dec) | +| Type | array (coins) | string (dec) | string (dec) | | Higher | More collateral required to bring an expedited proposal to vote | Easier for an expedited proposal to be passed | Longer expedited voting period | | Lower | Less collateral required to bring an expedited proposal to vote | Harder for an expedited proposal to be passed | Shorter expedited voting period | | Constraints | Value has to be a positive integer | Value has to be less or equal to `1` | Value has to be positive | -| Current configuration | `5000000000` (5000 OSMO) | `0.666666666666666667` (66.6%) | `86400000000000` (1 day) | +| Current configuration | `20000000000` (20000 OSMO) | `0.666666666666666667` (66.6%) | `86400000000000` (1 day) | diff --git a/docs/build/chain/ibc-hooks/README.md b/docs/build/chain/ibc-hooks/README.md index e28fa47a1..89a6fe18b 100644 --- a/docs/build/chain/ibc-hooks/README.md +++ b/docs/build/chain/ibc-hooks/README.md @@ -46,11 +46,12 @@ msg := MsgExecuteContract{ // Sender is the that actor that signed the messages Sender: "osmo1-hash-of-channel-and-sender", // Contract is the address of the smart contract - Contract: packet.data.memo["wasm"]["ContractAddress"], + Contract: packet.data.memo["wasm"]["contract"], // Msg json encoded message to be passed to the contract - Msg: packet.data.memo["wasm"]["Msg"], + Msg: packet.data.memo["wasm"]["msg"], // Funds coins that are transferred to the contract on execution - Funds: sdk.NewCoin{Denom: ibc.ConvertSenderDenomToLocalDenom(packet.data.Denom), Amount: packet.data.Amount} + Funds: sdk.NewCoins(sdk.NewCoin(ibc.ConvertSenderDenomToLocalDenom(packet.data.Denom), packet.data.Amount)), +} ``` ### ICS20 packet structure @@ -70,7 +71,7 @@ ICS20 is JSON native, so we use JSON for the memo format. "wasm": { "contract": "osmo1contractAddr", "msg": { - "raw_message_fields": "raw_message_data", + "raw_message_fields": "raw_message_data" } } } @@ -82,7 +83,7 @@ An ICS20 packet is formatted correctly for wasmhooks iff the following all hold: * `memo` is not blank * `memo` is valid JSON -* `memo` has at least one key, with value `"wasm"` +* `memo` has at least one key, with name `"wasm"` * `memo["wasm"]` has exactly two entries, `"contract"` and `"msg"` * `memo["wasm"]["msg"]` is a valid JSON object * `receiver == "" || receiver == memo["wasm"]["contract"]` @@ -100,7 +101,7 @@ If an ICS20 packet is directed towards wasmhooks, and is formatted incorrectly, Pre wasm hooks: -* Ensure the incoming IBC packet is cryptogaphically valid +* Ensure the incoming IBC packet is cryptographically valid * Ensure the incoming IBC packet is not timed out. In Wasm hooks, pre packet execution: @@ -132,7 +133,7 @@ Crucially, _only_ the IBC packet sender can set the callback. The crosschain swaps implementation sends an IBC transfer. If the transfer were to fail, we want to allow the sender to be able to retrieve their funds (which would otherwise be stuck in the contract). To do this, we allow users to retrieve the funds after the timeout has passed, but without the ack information, we cannot guarantee that the send -hasn't failed (i.e.: returned an error ack notifying that the receiving change didn't accept it) +hasn't failed (i.e.: returned an error ack notifying that the receiving chain didn't accept it) ### Implementation @@ -160,7 +161,7 @@ pub enum IBCLifecycleComplete { sequence: u64, /// String encoded version of the ack as seen by OnAcknowledgementPacket(..) ack: String, - /// Weather an ack is a success of failure according to the transfer spec + /// Whether an ack is a success or failure according to the transfer spec success: bool, }, #[serde(rename = "ibc_timeout")] @@ -180,6 +181,126 @@ pub enum SudoMsg { } ``` +### Async Acks + +IBC supports the ability to send an ack back to the sender of the packet asynchronously. This is useful for +cases where the packet is received, but the ack is not immediately known. For example, if the packet is being +forwarded to another chain, the ack may not be known until the packet is received on the other chain. + +Note this ACK does not imply full revertability. It is possible that unrevertable actions have occurred +even if there is an Ack Error. (This is distinct from the behavior of ICS-20 transfers). If you want to ensure +revertability, your contract should be implemented in a way that actions are not finalized until a success ack +is received. + +#### Use case + +Async acks are useful in cases where the contract needs to wait for a response from another chain before +returning a result to the caller. + +For example, if you want to send tokens to another chain after the contract is executed you need to +add a new ibc packet and wait for its ack. + +In the synchronous acks case, the caller will receive an ack from the contract before the second packet +has been processed. This means that the caller will have to wait (and potentially track) if the second +packet has been processed successfully or not. + +With async acks, your contract can take this responsibility and only send an ack to the caller once the +second packet has been processed. + +#### Making contract Acks async + +To support this, we allow contracts to return an `IBCAsync` response from the function being executed when the +packet is received. That response specifies that the ack should be handled asynchronously. + +Concretely the contract should return: + +```rust +#[cw_serde] +pub struct OnRecvPacketAsyncResponse { + pub is_async_ack: bool, +} +``` + +If `is_async_ack` is set to true, `OnRecvPacket` will return `nil` and the ack will not be written. Instead, the +contract will be stored as the "ack actor" for the packet so that only that contract is allowed to send an ack +for it. + +It is up to the contract developers to decide which conditions will trigger the ack to be sent. + +#### Sending an async ack + +To send the async ack, the contract needs to send the `MsgEmitIBCAck` message to the chain. This message will +then make a sudo call to the contract requesting the ack and write the ack to state. + +That message can be specified in the contract as: + +```rust +#[derive( + Clone, + PartialEq, + Eq, + ::prost::Message, + serde::Serialize, + serde::Deserialize, + schemars::JsonSchema, + CosmwasmExt, +)] +#[proto_message(type_url = "/osmosis.ibchooks.MsgEmitIBCAck")] +pub struct MsgEmitIBCAck { + #[prost(string, tag = "1")] + pub sender: ::prost::alloc::string::String, + #[prost(uint64, tag = "2")] + pub packet_sequence: u64, + #[prost(string, tag = "3")] + pub channel: ::prost::alloc::string::String, +} +``` + +The contract is expected to implement the following sudo message handler: + +```rust +#[cw_serde] +pub enum IBCAsyncOptions { + #[serde(rename = "request_ack")] + RequestAck { + /// The source channel (osmosis side) of the IBC packet + source_channel: String, + /// The sequence number that the packet was sent with + packet_sequence: u64, + }, +} + +#[cw_serde] +pub enum SudoMsg { + #[serde(rename = "ibc_async")] + IBCAsync(IBCAsyncOptions), +} +``` + +and that sudo call should return an `IBCAckResponse`: + +```rust +#[cw_serde] +#[serde(tag = "type", content = "content")] +pub enum IBCAck { + AckResponse{ + packet: Packet, + contract_ack: ContractAck, + }, + AckError { + packet: Packet, + error_description: String, + error_response: String, + } +} +``` + +Note: the sudo call is required to potentially allow anyone to send the `MsgEmitIBCAck` message. For now, however, +this is artificially limited so that the message can only be sent by the same contract. This could be expanded in +the future if needed. + +The `MsgEmitIBCAck` message is defined in the [`osmosis.ibchooks` proto](https://github.com/osmosis-labs/osmosis/blob/main/proto/osmosis/ibchooks/tx.proto) at the `v31.0.1` tag. + # Testing strategy See go tests. \ No newline at end of file diff --git a/docs/build/chain/ibc-rate-limit/README.md b/docs/build/chain/ibc-rate-limit/README.md index 10f521c8a..447659b67 100644 --- a/docs/build/chain/ibc-rate-limit/README.md +++ b/docs/build/chain/ibc-rate-limit/README.md @@ -297,7 +297,7 @@ Not yet highlighted * Making monitoring tooling to know when approaching rate limiting and when they're hit * Making tooling to easily give us summaries we can use, to reason about "bug or not bug" in event of rate limit being hit * Enabling ways to pre-declare large transfers so as to not hit rate limits. - * Perhaps you can on-chain declare intent to send these assets with a large delay, that raises monitoring but bypasses rate limits? + * Perhaps you can onchain declare intent to send these assets with a large delay, that raises monitoring but bypasses rate limits? * Maybe contract-based tooling to split up the transfer suffices? * Strategies to account for high volatility periods without hitting rate limits * Can imagine "Hop network" style markets emerging diff --git a/docs/build/chain/incentives/README.md b/docs/build/chain/incentives/README.md index 9db31858b..8ee9a2996 100644 --- a/docs/build/chain/incentives/README.md +++ b/docs/build/chain/incentives/README.md @@ -30,7 +30,7 @@ There are two kinds of `gauges`, perpetual and non-perpetual ones. The purpose of `incentives` module is to provide incentives to the users who lock specific token for specific period of time. -Locked tokens can be of any denomination, including LP tokens (gamm/pool/x), IBC tokens (tokens sent through IBC such as ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2), and native tokens (such as ATOM or LUNA). +Locked tokens can be of any denomination, including LP tokens (gamm/pool/x), IBC tokens (tokens sent through IBC such as ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2), and native tokens (such as uosmo). The incentive amount is entered by the gauge creator. Rewards for a given pool of locked up tokens are pooled into a gauge until the disbursement time. At the disbursement time, they are distributed pro-rata (proportionally) to members of the pool. @@ -74,10 +74,13 @@ message QueryCondition { message Gauge { uint64 id = 1; // unique ID of a Gauge - QueryCondition distribute_to = 2; // distribute condition of a lock which meets one of these conditions - repeated cosmos.base.v1beta1.Coin coins = 3; // can distribute multiple coins - google.protobuf.Timestamp start_time = 4; // condition for lock start time, not valid if unset value - uint64 num_epochs_paid_over = 5; // number of epochs distribution will be done + bool is_perpetual = 2; // flag to show if it's a perpetual or non-perpetual gauge + QueryCondition distribute_to = 3; // distribute condition of a lock which meets one of these conditions + repeated cosmos.base.v1beta1.Coin coins = 4; // can distribute multiple coins + google.protobuf.Timestamp start_time = 5; // condition for lock start time, not valid if unset value + uint64 num_epochs_paid_over = 6; // number of epochs distribution will be done + uint64 filled_epochs = 7; // number of epochs distribution has been completed already + repeated cosmos.base.v1beta1.Coin distributed_coins = 8; // coins that have been distributed already } ``` @@ -130,11 +133,13 @@ message GenesisState { ```go type MsgCreateGauge struct { - Owner sdk.AccAddress + IsPerpetual bool // perpetual gauge flag (set by the --perpetual flag) + Owner sdk.AccAddress DistributeTo QueryCondition - Rewards sdk.Coins + Coins sdk.Coins StartTime time.Time // start time to start distribution NumEpochsPaidOver uint64 // number of epochs distribution will be done + PoolId uint64 // pool the gauge is associated with (NoLock gauges) } ``` @@ -164,6 +169,30 @@ type MsgAddToGauge struct { - Modify the `Gauge` record by adding `msg.Rewards` - Transfer the tokens from the `Owner` to incentives `ModuleAccount`. +### Create Group + +`MsgCreateGroup` can be submitted by any account to create a `Group` that +distributes rewards across a set of pools. The group is 1:1 mapped to a group +gauge that allocates rewards dynamically across the internal gauges of its +member pools based on a volume splitting policy. Only perpetual pool gauges can +be associated with a group, and the group must contain at least two pools. + +```go +type MsgCreateGroup struct { + Coins sdk.Coins + NumEpochsPaidOver uint64 // number of epochs distribution will be done; 0 means perpetual + Owner sdk.AccAddress + PoolIds []uint64 // pools the group is comprised of +} +``` + +**State modifications:** + +- Create the `Group` and its 1:1 group `Gauge` +- For each `PoolId`, use the pool's main internal gauge to create the gauge records associated with the `Group` +- Sync the group's weights, failing creation if any pool is invalid or has no associated volume +- Charge the group creation fee and transfer the tokens from the `Owner` to incentives `ModuleAccount` + ## Transactions ### create-gauge @@ -177,7 +206,7 @@ osmosisd tx incentives create-gauge [lockup_denom] [reward] [flags] **Example 1** I want to make incentives for LP tokens of pool 3, namely gamm/pool/3 that have been locked up for at least 14 days. [this is currently the only valid bonding period] -I want to reward 100 AKT to this pool over 2 days (2 epochs). (50 rewarded on each day) +I want to reward 10000 base units of ibc/1480B8FD20AD5FCAE81EA87584D269547DD4D436843C1D20F15E00EB64743EF4 to this pool over 2 days (2 epochs). (5000 rewarded on each day) I want the rewards to start dispersing on 21 December 2021 (1640081402 UNIX time) ```bash @@ -239,8 +268,8 @@ The incentives module emits the following events: | Type | Attribute Key | Attribute Value | | ------------ | ------------- | --------------- | | add_to_gauge | gauge_id | `{gaugeID}` | -| create_gauge | rewards | `{rewards}` | -| message | action | create_gauge | +| add_to_gauge | rewards | `{rewards}` | +| message | action | add_to_gauge | | message | sender | `{owner}` | | transfer | recipient | `{moduleAccount}` | | transfer | sender | `{owner}` | diff --git a/docs/build/chain/lockup/README.md b/docs/build/chain/lockup/README.md index 06f60c855..ab5a54d76 100644 --- a/docs/build/chain/lockup/README.md +++ b/docs/build/chain/lockup/README.md @@ -4,9 +4,9 @@ Lockup module provides an interface for users to lock tokens (also known as bonding) into the module to get incentives. -After tokens have been added to a specific pool and turned into LP shares through the GAMM module, users can then lock these LP shares with a specific duration in order to begin earing rewards. +The module is denom-agnostic: `MsgLockTokens` accepts any token. The most common case is GAMM LP shares (`gamm/pool/N` denoms), which a user receives after adding liquidity to a pool through the GAMM module and can then lock with a specific duration in order to begin earning rewards. The module also issues synthetic lock denoms used by superfluid and delegated staking. -To unlock these LP shares, users must trigger the unlock timer and wait for the unlock period that was set initially to be completed. After the unlock period is over, users can turn LP shares back into their respective share of tokens. +To unlock locked tokens, users must trigger the unlock timer and wait for the unlock period that was set initially to be completed. After the unlock period is over, the tokens are returned to the owner. This module provides interfaces for other modules to iterate the locks efficiently and grpc query to check the status of locked coins. @@ -210,7 +210,7 @@ already finished, we manage a separate time basis queue at ``` {.go} type MsgLockTokens struct { - Owner sdk.AccAddress + Owner string Duration time.Duration Coins sdk.Coins } @@ -265,6 +265,59 @@ type MsgBeginUnlocking struct { Note: If another module needs past `PeriodLock` item, it can log the details themselves using the hooks. +### Extend Lockup + +`MsgExtendLockup` extends the duration of an existing, not-yet-unlocking lock to a longer duration. + +``` {.go} +type MsgExtendLockup struct { + Owner string + ID uint64 + Duration time.Duration +} +``` + +**State modifications:** + +- Check the `PeriodLock` with `ID` is owned by `Owner` and has not started unlocking +- Update the lock's `Duration` to the new (longer) value +- Update the duration-based reference queues for the lock + +### Force Unlock + +`MsgForceUnlock` unlocks a lock without the time check. The sender must be in the `ForceUnlockAllowedAddresses` parameter allowlist. + +``` {.go} +type MsgForceUnlock struct { + Owner string + ID uint64 + Coins sdk.Coins +} +``` + +**State modifications:** + +- Verify the sender is in the `ForceUnlockAllowedAddresses` allowlist +- Unlock the `PeriodLock` with `ID` (full amount if `Coins` is empty, otherwise the specified `Coins`) +- Transfer the unlocked tokens from the lockup `ModuleAccount` to the `Owner` + +### Set Reward Receiver Address + +`MsgSetRewardReceiverAddress` sets the address that receives lockup incentive rewards for a given lock, allowing rewards to be redirected away from the lock owner. + +``` {.go} +type MsgSetRewardReceiverAddress struct { + Owner string + LockID uint64 + RewardReceiver string +} +``` + +**State modifications:** + +- Check the `PeriodLock` with `LockID` is owned by `Owner` +- Set the lock's reward receiver address to `RewardReceiver` + ## Events The lockup module emits the following events: @@ -323,8 +376,8 @@ The lockup module emits the following events: | transfer\[\] | recipient | `{owner}` | | transfer\[\] | sender | `{moduleAccount}` | | transfer\[\] | amount | `{unlockAmount}` | -| unlock\[\] | period\_lock\_id | `{owner}` | -| unlock\[\] | owner | `{lockID}` | +| unlock\[\] | period\_lock\_id | `{periodLockID}` | +| unlock\[\] | owner | `{owner}` | | unlock\[\] | duration | `{lockDuration}` | | unlock\[\] | unlock\_time | `{unlockTime}` | | unlock\_tokens | owner | `{owner}` | @@ -432,11 +485,9 @@ make following actions. The lockup module contains the following parameters: -| Key | Type | Example | -| ---------------------- | --------------- | ------- | - -Note: Currently no parameters are set for `lockup` module, we will need -to move lockable durations from incentives module to lockup module. +| Key | Type | Description | +| -------------------------------- | ---------- | -------------------------------------------------------------------------------------------------------- | +| `force_unlock_allowed_addresses` | `[]string` | Governance-managed allowlist of addresses permitted to call `MsgForceUnlock` (unlock without time check). | ## Endblocker @@ -468,7 +519,7 @@ reference queues are removed. ### lock-tokens -Bond tokens in a LP for a set duration +Lock tokens (typically LP shares, or any other lockable denom) for a set duration ```sh osmosisd tx lockup lock-tokens [tokens] --duration --from --chain-id @@ -565,8 +616,18 @@ service Query { // Returns lock records by address, timestamp, denom rpc AccountLockedPastTimeDenom(AccountLockedPastTimeDenomRequest) returns (AccountLockedPastTimeDenomResponse); + // Returns total locked per denom with longer past given time + rpc LockedDenom(LockedDenomRequest) returns (LockedDenomResponse); // Returns lock record by id rpc LockedByID(LockedRequest) returns (LockedResponse); + // Returns lock record by id + rpc LockRewardReceiver(LockRewardReceiverRequest) returns (LockRewardReceiverResponse); + // Returns next lock ID + rpc NextLockID(NextLockIDRequest) returns (NextLockIDResponse); + // Returns synthetic lockups by native lockup id (Deprecated: use SyntheticLockupByLockupID instead) + rpc SyntheticLockupsByLockupID(SyntheticLockupsByLockupIDRequest) returns (SyntheticLockupsByLockupIDResponse); + // Returns synthetic lockup by native lockup id + rpc SyntheticLockupByLockupID(SyntheticLockupByLockupIDRequest) returns (SyntheticLockupByLockupIDResponse); // Returns account locked records with longer duration rpc AccountLockedLongerDuration(AccountLockedLongerDurationRequest) returns (AccountLockedLongerDurationResponse); @@ -577,6 +638,8 @@ service Query { // Returns account locked records with a specific duration rpc AccountLockedDuration(AccountLockedDurationRequest) returns (AccountLockedDurationResponse); + // Params returns lockup params + rpc Params(QueryParamsRequest) returns (QueryParamsResponse); } ``` @@ -1137,10 +1200,11 @@ osmosisd tx lockup lock-tokens 100stake --duration="5s" --from=validator --chain # begin unlock tokens, NOTE: add more gas when unlocking more than two locks in a same command osmosisd tx lockup begin-unlock-tokens --from=validator --gas=500000 --chain-id=testing --keyring-backend=test --yes -# unlock tokens, NOTE: add more gas when unlocking more than two locks in a same command +# DEPRECATED (retained only for indexing; use begin-unlock-tokens instead). Unlocking now completes +# automatically at the EndBlocker once the lock duration elapses after begin-unlock. osmosisd tx lockup unlock-tokens --from=validator --gas=500000 --chain-id=testing --keyring-backend=test --yes -# unlock specific period lock +# DEPRECATED (retained only for indexing; use begin-unlock-by-id instead). osmosisd tx lockup unlock-by-id 1 --from=validator --chain-id=testing --keyring-backend=test --yes # account balance diff --git a/docs/build/chain/mint/README.md b/docs/build/chain/mint/README.md index f9568d4b5..a51e96dd5 100644 --- a/docs/build/chain/mint/README.md +++ b/docs/build/chain/mint/README.md @@ -48,7 +48,7 @@ the following formula: ### Minter -The [`Minter`](https://github.com/osmosis-labs/osmosis/blob/cbb683e8395655042b4421355cd54a8c96bfa507/x/mint/types/mint.pb.go#L30) is an abstraction for holding current rewards information. +The [`Minter`](https://github.com/osmosis-labs/osmosis/blob/main/proto/osmosis/mint/v1beta1/mint.proto#L12) is an abstraction for holding current rewards information. ```go type Minter struct { @@ -158,7 +158,7 @@ query mint params
Example -List all current min parameters in json format by: +List all current mint parameters in json format by: ```bash osmosisd query mint params -o json | jq @@ -281,4 +281,4 @@ The following tables show overall effects on different configurations of the `mi | Higher | N/A | Higher inflation rate | Increases time to reduction_period | | Lower | N/A | Lower inflation rate | Decreases time to reduction_period | | Constraints | N/A | Value has to be a positive integer | String must be day, week, month, or year | -| Current configuration | uosmo | 821917808219.178 (821,9178 OSMO) | day | +| Current configuration | uosmo | 821917808219.178 (821,917.808 OSMO) | day | diff --git a/docs/build/chain/pool-incentives/README.md b/docs/build/chain/pool-incentives/README.md index bf77a3582..5db7a84a7 100644 --- a/docs/build/chain/pool-incentives/README.md +++ b/docs/build/chain/pool-incentives/README.md @@ -2,7 +2,7 @@ ## Abstract -The `pool-incentives` module is separate but related to the `incentives` module. When a pool is created using the `GAMM` module, the `pool-incentives` module automatically creates individual gauges in the `incentives` module for every lock duration that exists in that pool. +The `pool-incentives` module is separate but related to the `incentives` module. When a pool is created (pool creation is handled by the `poolmanager` module), the `pool-incentives` module automatically creates gauges in the `incentives` module. For GAMM/balancer pools it creates one gauge per lock duration that exists in that pool; for concentrated liquidity pools it creates a single gauge. The `pool-incentives` module also takes the `pool_incentives` distributed from the `gov` module and distributes it to the various incentivized gauges. ## Contents @@ -10,7 +10,7 @@ The `pool-incentives` module also takes the `pool_incentives` distributed from t 1. **[Concept](#concepts)** 2. **[State](#state)** 3. **[Governance](#gov)** -4. **[Transactions](#transactions)** +4. **[Governance proposals](#governance-proposals)** 5. **[Queries](#queries)** ## Concepts @@ -33,9 +33,13 @@ selected gauges. ```go type GenesisState struct { // params defines all the parameters of the module. - Params Params - LockableDurations []time.Duration - DistrInfo *DistrInfo + Params Params + LockableDurations []time.Duration + DistrInfo *DistrInfo + // any_pool_to_internal_gauges links every pool to its internal gauges. + AnyPoolToInternalGauges *AnyPoolToInternalGauges + // concentrated_pool_to_no_lock_gauges links concentrated pools to their no-lock gauges. + ConcentratedPoolToNoLockGauges *ConcentratedPoolToNoLockGauges } type Params struct { @@ -44,9 +48,6 @@ type Params struct { // Pool-incentives module doesn’t actually mint the coin itself, // but rather manages the distribution of coins that matches the defined minted_denom. MintedDenom string - // allocation_ratio defines the proportion of the minted minted_denom - // that is to be allocated as pool incentives. - AllocationRatio github_com_cosmos_cosmos_sdk_types.Dec } ``` @@ -56,13 +57,11 @@ same amount of 'gauge' as there are lockable durations for the pool. Also in regards to the `Params`, when the mint module mints new tokens to the fee collector at Begin Block, the `pool incentives` module takes -the token which matches the 'minted denom' from the fee collector. -Tokens are taken according to the 'allocationRatio', and are distributed -to each `DistrRecord` of the DistrInfo. For example, if the fee -collector holds 1000uatom and 2000 uosmo at Begin Block, and Params' -mintedDenom is set to uosmo, and AllocationRatio is set to 0.1, 200uosmo -will be taken from the fee collector and distributed to the -`DistrRecord`s. +the token which matches the 'minted denom' from the fee collector and +distributes it to each `DistrRecord` of the DistrInfo. The share of the +minted inflation routed to pool incentives is governed by the mint +module's `pool_incentives` distribution proportion, not by a +pool-incentives parameter. ## Gov @@ -111,83 +110,43 @@ gauge id 3, the following command can be used. osmosisd tx gov submit-proposal update-pool-incentives 2,3 100,200 ``` -## Transactions +## Governance proposals + +The `pool-incentives` module registers no `tx poolincentives` subcommands (`GetTxCmd` returns `nil`). `DistrInfo` is modified through governance, using the `ReplacePoolIncentivesProposal` and `UpdatePoolIncentivesProposal` content types submitted via `x/gov`. Both proposals carry the same payload (`title`, `description`, and a list of `DistrRecord`s); they differ only in how the records are applied: + +- **replace-pool-incentives** (`ReplacePoolIncentivesProposal`): the proposal's records override the existing `DistrRecord`s in the module (a full overwrite). +- **update-pool-incentives** (`UpdatePoolIncentivesProposal`): the proposal edits or adds only the `DistrRecord`s it specifies, leaving other records in place. -### replace-pool-incentives +### replace-pool-incentives ```sh -osmosisd tx poolincentives replace-pool-incentives [gaugeIds] [weights] [flags] +osmosisd tx gov submit-proposal replace-pool-incentives [gaugeIds] [weights] [flags] ```
Example -Fully replace records for pool incentives: +Fully replace the records for pool incentives, designating 100 weight to gauge id 2 and 200 weight to gauge id 3: ```bash -osmosisd tx poolincentives replace-pool-incentives proposal.json --from --chain-id -``` - -The proposal.json would look as follows: - -```json -{ - "title": "Pool Incentive Adjustment", - "description": "Adjust pool incentives", - "records": [ - { - "gauge_id": "0", - "weight": "100000" - }, - { - "gauge_id": "1", - "weight": "1766249" - }, - { - "gauge_id": "XXX", - "weight": "XXXXXXXX" - }, - ... - ] -} +osmosisd tx gov submit-proposal replace-pool-incentives 2,3 100,200 --from WALLET_NAME --chain-id CHAIN_ID ```
-### update-pool-incentives - -Update the weight of specified pool gauges in regards to their share of incentives (by creating a proposal) +### update-pool-incentives ```sh -osmosisd tx poolincentives update-pool-incentives [gaugeIds] [weights] [flags] --from --chain-id +osmosisd tx gov submit-proposal update-pool-incentives [gaugeIds] [weights] [flags] ```
Example -Update the pool incentives for `gauge_id` 0 and 1: +Update only the specified gauges, designating 100 weight to gauge id 2 and 200 weight to gauge id 3: ```bash -osmosisd tx gov submit-proposal update-pool-incentives proposal.json --from WALLET_NAME --chain-id CHAIN_ID -``` - -The proposal.json would look as follows: - -```json -{ - "title": "Pool Incentive Adjustment", - "description": "Adjust pool incentives", - "records": [ - { - "gauge_id": "0", - "weight": "100000" - }, - { - "gauge_id": "1", - "weight": "1766249" - }, - ] -} +osmosisd tx gov submit-proposal update-pool-incentives 2,3 100,200 --from WALLET_NAME --chain-id CHAIN_ID ```
diff --git a/docs/build/chain/pool-manager/README.md b/docs/build/chain/pool-manager/README.md index c58a6331e..63582c32b 100644 --- a/docs/build/chain/pool-manager/README.md +++ b/docs/build/chain/pool-manager/README.md @@ -3,7 +3,7 @@ The poolmanager module exists as a swap entrypoint for any pool model that exists on the chain. The poolmanager module is responsible for routing swaps across various pools. It also performs pool-id management for -any on-chain pool. +any onchain pool. The user-stories for this module follow: diff --git a/docs/build/chain/protorev/README.md b/docs/build/chain/protorev/README.md index 161fb7cd3..589c60d6c 100644 --- a/docs/build/chain/protorev/README.md +++ b/docs/build/chain/protorev/README.md @@ -78,15 +78,15 @@ The `x/protorev` module keeps the following objects in state: | State Object | Description | Key | Values | Store | | --- | --- | --- | --- | --- | | TokenPairArbRoutes | TokenPairRoutes tracks cyclic arb routes that can be used to create a MultiHopSwap given two denoms | `[]byte{1}` + `[]byte{inputDenom}` +`[]byte{outputDenom}` | `[]byte{TokenPairArbRoutes}` | KV | -| DenomPairToPool | Tracks the pool ids of the highest liquidity pools matched with a given denom`[]byte{2}` | `[]byte{2}` + `[]byte{baseDenom}` + `[]byte{denomToMatch}` | `[]byte{poolID}` | KV | -| BaseDenoms | Tracks all of the base denominations that will be used to construct arbitrage routes | `[]byte{3}` | `[]byte{[]BaseDenoms{}`} | KV | +| DenomPairToPool | Tracks the pool ids of the highest liquidity pools matched with a given denom | `[]byte{2}` + `[]byte{baseDenom}` + `[]byte{denomToMatch}` | `[]byte{poolID}` | KV | +| BaseDenoms | Tracks all of the base denominations that will be used to construct arbitrage routes | `[]byte{3}` | `[]byte{[]BaseDenom{}}` | KV | | NumberOfTrades | Tracks the number of trades protorev has executed | `[]byte{4}` | `[]byte{numberOfTrades}` | KV | | ProfitsByDenom | Tracks the profits protorev has made | `[]byte{5}` + `[]byte{tokenDenom}` | `[]byte{sdk.Coin}` | KV | | TradesByRoute | Tracks the number of trades the module has executed on a given route | `[]byte{6}` + `[]byte{route}` | `[]byte{numberOfTrades}` | KV | | ProfitsByRoute | Tracks the profits the module has accumulated after trading on a given route | `[]byte{7}` + `[]byte{route}` | `[]byte{sdk.Coin}` | KV | | DeveloperAccount | Tracks the developer account for protorev | `[]byte{8}` | `[]byte{sdk.AccAddress}` | KV | | DaysSinceModuleGenesis | Tracks the number of days since the module was initialized. Used to track profits that can be withdrawn by the developer account | `[]byte{9}` | `[]byte{uint}` | KV | -| DeveloperFees | Tracks the profits that the developer account can withdraw | `[]byte{10}` + `[]byte{tokenDenom}` | `[]byte{sdk.Coin}` | KV | +| DeveloperFees (deprecated in v16) | Tracks the profits that the developer account can withdraw | `[]byte{10}` + `[]byte{tokenDenom}` | `[]byte{sdk.Coin}` | KV | | MaxPoolPointsPerTx | Tracks the maximum number of pool points that can be consumed per tx | `[]byte{11}` | `[]byte{uint64}` | KV | | MaxPoolPointsPerBlock | Tracks the maximum number of pool points that can be consumed per block | `[]byte{12}` | `[]byte{uint64}` | KV | | PoolPointCountForBlock | Tracks the number of pool points that have been consumed in this block | `[]byte{13}` | `[]byte{uint64}` | KV | @@ -141,7 +141,7 @@ message Trade { ### DenomPairToPool -DenomPairToPool takes in a base denomination (read below) – denom that is used to build routes (ex. osmo, atom, usdc) – and a denom to match (akash, juno) and returns the highest liquidity pool id between the pair of denominations. For example, an input might look like (osmo, juno) —> poolID: 5. This store is directly tied to the highest liquidity method (described in state transitions below). Each base denomination is going to have its own set of denominations it maps to. +DenomPairToPool takes in a base denomination (read below), the denom that is used to build routes (ex. osmo, atom, usdc), and a denom to match (akash, juno), and returns the highest liquidity pool id between the pair of denominations. For example, an input might look like (osmo, juno) -> poolID: 5. This store is directly tied to the highest liquidity method (described in state transitions below). Each base denomination is going to have its own set of denominations it maps to. ### BaseDenoms @@ -167,7 +167,7 @@ These stores allow users and researchers to query the number of cyclic arbitrage ### AdminAccount -The admin account is set through governance and has permissions to set hot routes, the maximum number of pool points per transaction, maximum number of pool points per block, pool type weights, base denoms and the developer account. On genesis, the admin account is set to a trusted address that is stored on a ledger - currently configured to be the Skip dev team's address. Note that governance has full ability to change this live on-chain, and this admin can at most prevent `x/protorev` from working. All the admin account's controls have limits, so it can't lead to a chain halt, excess processing time or prevention of swaps. +The admin account is set through governance and has permissions to set hot routes, the maximum number of pool points per transaction, maximum number of pool points per block, pool type weights, base denoms and the developer account. On genesis, the admin account is set to a trusted address that is stored on a ledger - currently configured to be the Skip dev team's address. Note that governance has full ability to change this live onchain, and this admin can at most prevent `x/protorev` from working. All the admin account's controls have limits, so it can't lead to a chain halt, excess processing time or prevention of swaps. ### DeveloperAccount @@ -219,7 +219,7 @@ type PoolWeights struct { ### GenesisState -There is only one configurable parameter for the genesis state —> whether protorev is enabled or not. +There is only one configurable parameter for the genesis state -> whether protorev is enabled or not. ```go // GenesisState defines the protorev module's genesis state. @@ -250,13 +250,13 @@ BaseDenoms - Osmosis - Atom -Lets say the `postHandler` receives a transaction that contains a swap of **Juno** —> **Akash** on pool **4**. In this case, the module will attempt to create three-pool route where a base denomination is on either side of the route. For example, a route that it might create is +Lets say the `postHandler` receives a transaction that contains a swap of **Juno** -> **Akash** on pool **4**. In this case, the module will attempt to create three-pool route where a base denomination is on either side of the route. For example, a route that it might create is -- Osmosis —> Akash (on pool 1), Akash —> Juno (on pool 4), Juno —> Osmosis (on pool 2) +- Osmosis -> Akash (on pool 1), Akash -> Juno (on pool 4), Juno -> Osmosis (on pool 2) -It does so by finding the highest liquidity pool between (Osmosis, Akash) —> pool 1 and the highest liquidity pool between (Osmosis, Juno) —> pool 2. If there is no highest liquidity pool pair between (Osmosis, Juno) or (Osmosis, Akash), no route will be generated. +It does so by finding the highest liquidity pool between (Osmosis, Akash) -> pool 1 and the highest liquidity pool between (Osmosis, Juno) -> pool 2. If there is no highest liquidity pool pair between (Osmosis, Juno) or (Osmosis, Akash), no route will be generated. -**NOTE: Cyclic arbitrage routes will always go in the opposite direction of the original swap i.e. in this case we see Juno —> Akash so we know that the route must include a swap of Akash —> Juno.** +**NOTE: Cyclic arbitrage routes will always go in the opposite direction of the original swap i.e. in this case we see Juno -> Akash so we know that the route must include a swap of Akash -> Juno.** The same line of reasoning exists for Atom. `x/protorev` will attempt to find the highest liquidity pool between (Atom, Akash) and (Atom, Juno). If these pools exist, they will be added to the list of routes that can be simulated later in the pipeline. If not, the route is discarded. @@ -276,20 +276,6 @@ Each swap will generate its own set of routes and `x/protorev` will execute only The module mints the optimal input amount of the coin to swap in from the `bankkeeper` to the `x/protorev` module account, executes the MultiHopSwap by interacting with the `x/poolmanager` module, burns the optimal input amount of the coin minted to execute the MultiHopSwap, and sends subsequent profits to the module account. -## Governance Proposals - -`x/protorev` implements two different governance proposals. - -**SetProtoRevAdminAccountProposal** - -As the landscape of pools on Osmosis evolves, an admin account will be able to add and remove routes for `x/protorev` to check for cyclic arbitrage opportunities along with several other optimization txs. Largely, the purpose of maintaining hot routes is to reduce the amount of computation that would otherwise be required to determine optimal paths at runtime. - -This proposal is put in place in case the admin account needs to be transferred over. However, as mentioned above, it will be initialized to a trusted address on genesis. - -**SetProtoRevEnabledProposal** - -This proposal type allows the chain to turn the module on or off. This is meant to be used as a fail safe in the case stakers and the chain decide to turn the module off. This might be used to halt the execution of trades in the case that the `x/gamm` module has significant upgrades that might produce unexpected behavior from the module. - ## PostHandler The `postHandler` extracts pools that were swapped in a transaction and determines if there is a cyclic arbitrage opportunity. If so, the handler will find an optimal route and execute it - rebalancing the pool and returning arbitrage profits to the module account. diff --git a/docs/build/chain/superfluid/README.md b/docs/build/chain/superfluid/README.md index 9dadd46ed..f8744b760 100644 --- a/docs/build/chain/superfluid/README.md +++ b/docs/build/chain/superfluid/README.md @@ -6,7 +6,9 @@ Superfluid Staking provides the consensus layer more security with a sort of "Proof of Useful Stake". Each person gets an amount of Osmo representative of the value of their share of liquidity pool tokens staked and delegated to validators, resulting in the security guarantee -of the consensus layer to also be based on GAMM LP shares. The OSMO +of the consensus layer to also be based on liquidity provider positions. +Superfluid staking supports both GAMM LP shares and full-range +concentrated-liquidity positions as the underlying staked asset. The OSMO token is minted and burned in the context of Superfluid Staking. Throughout all of this, OSMO's supply is preserved in queries to the bank module. @@ -54,7 +56,7 @@ modules](https://github.com/osmosis-labs/osmosis/tree/main/x/superfluid). ### Example -If Alice has 500 GAMM tokens bonded to the ATOM \<\> OSMO, she will have +If Alice has 500 GAMM tokens bonded to the ATOM/OSMO pool, she will have the equivalent value of OSMO minted, delegated to her chosen staker, and burned for her each day with Superfluid staking. On the user side, all she has to know is who she wants to delegate her tokens to. In order to @@ -185,12 +187,15 @@ A superfluid asset is an alternative asset (non-OSMO) that is allowed by governance to be used for staking. It can only be updated by governance proposals. We validate at proposal -creation time that the denom + pool exists. (Are we going to ignore edge -cases around a reference pool getting deleted it) +creation time that the denom + pool exists. ### Intermediary Accounts -Lots of questions to be answered here +An intermediary account exists for every (superfluid denom, validator) +pair. It holds the minted OSMO that represents the value of the locks +grouped under that pair and performs the actual delegation to the +validator on their behalf. Each intermediary account has a dedicated +perpetual gauge to which its delegation rewards are sent. ### Dedicated Gauges @@ -347,6 +352,97 @@ lock until after the unstaking has finished. - This runs the functionality of `MsgSuperfluidUndelegate` - It then triggers a force unbond of the underlying lock id +### Superfluid Undelegate and Unbond Lock + +```{.go} +type MsgSuperfluidUndelegateAndUnbondLock struct { + Sender string + LockId uint64 + Coin sdk.Coin +} +``` + +Undelegates and starts unbonding for the specified `Coin` amount of the +given lock in a single message. Unlike `MsgSuperfluidUnbondLock`, the +caller specifies a coin amount, which allows unbonding only part of the +lock. + +### Create Full Range Position and Superfluid Delegate + +```{.go} +type MsgCreateFullRangePositionAndSuperfluidDelegate struct { + Sender string + Coins sdk.Coins + ValAddr string + PoolId uint64 +} +``` + +Creates a full-range position in the concentrated-liquidity pool +identified by `PoolId` from `Coins`, then superfluid delegates the +resulting position to `ValAddr`. This is the concentrated-liquidity +analogue of `MsgLockAndSuperfluidDelegate`. + +### Add to Concentrated Liquidity Superfluid Position + +```{.go} +type MsgAddToConcentratedLiquiditySuperfluidPosition struct { + PositionId uint64 + Sender string + TokenDesired0 sdk.Coin + TokenDesired1 sdk.Coin +} +``` + +Adds liquidity to an existing concentrated-liquidity superfluid position +identified by `PositionId`, using up to `TokenDesired0` and +`TokenDesired1`. + +### Unlock and Migrate Shares to Full Range Concentrated Position + +```{.go} +type MsgUnlockAndMigrateSharesToFullRangeConcentratedPosition struct { + Sender string + LockId int64 + SharesToMigrate sdk.Coin + TokenOutMins sdk.Coins +} +``` + +Unlocks `SharesToMigrate` GAMM shares from the lock identified by +`LockId` and migrates them into a full-range position in the linked +concentrated-liquidity pool. `TokenOutMins` sets minimum amounts out to +guard against slippage during migration. + +### Unbond, Convert, and Stake + +```{.go} +type MsgUnbondConvertAndStake struct { + LockId uint64 + Sender string + ValAddr string + MinAmtToStake sdk.Int + SharesToConvert sdk.Coin +} +``` + +Unbonds the lock identified by `LockId`, converts `SharesToConvert` GAMM +shares into OSMO, and stakes the result to `ValAddr`, requiring at least +`MinAmtToStake` OSMO to be staked. + +### Unpool Whitelisted Pool + +```{.go} +type MsgUnPoolWhitelistedPool struct { + Sender string + PoolId uint64 +} +``` + +Exits a governance-whitelisted pool, unlocking the underlying assets so +they can be withdrawn. This is the message that emits the +`TypeEvtUnpoolId` event documented in the Events section. + ## Epochs Overall Epoch sequence @@ -392,7 +488,7 @@ active set. We expect the guarantee that there is an Intermediary account for every (active validator, superfluid denom) pair, and every (unbonding -validator, superfluid denom) pair. (TODO: Where/why) +validator, superfluid denom) pair. We also want to avoid resource exhaustion attacks. We relegate concerns around upper-bounding the number of active + unbonding validators to the @@ -453,7 +549,7 @@ Disable multiple assets from being used for superfluid staking. ## Events -There are 7 types of events that exist in Superfluid module: +There are 11 types of events that exist in Superfluid module: * `types.TypeEvtSetSuperfluidAsset` - "set_superfluid_asset" * `types.TypeEvtRemoveSuperfluidAsset` - "remove_superfluid_asset" @@ -461,6 +557,10 @@ There are 7 types of events that exist in Superfluid module: * `types.TypeEvtSuperfluidIncreaseDelegation` - "superfluid_increase_delegation" * `types.TypeEvtSuperfluidUndelegate` - "superfluid_undelegate" * `types.TypeEvtSuperfluidUnbondLock` - "superfluid_unbond_lock" +* `types.TypeEvtSuperfluidUndelegateAndUnbondLock` - "superfluid_undelegate_and_unbond_lock" +* `types.TypeEvtAddToConcentratedLiquiditySuperfluidPosition` - "add_to_concentrated_liquidity_superfluid_position" +* `types.TypeEvtUnlockAndMigrateShares` - "unlock_and_migrate_shares" +* `types.TypeEvtCreateFullRangePositionAndSFDelegate` - "full_range_position_and_delegate" * `types.TypeEvtUnpoolId` - "unpool_pool_id" ### `types.TypeEvtSetSuperfluidAsset` @@ -523,6 +623,55 @@ It consists of the following attributes: * `types.AttributeLockId` * The value is the given lock ID. +### `types.TypeEvtSuperfluidUndelegateAndUnbondLock` + +This event is emitted in the message server after undelegating and starting unbonding for the given lock in a single message. + +It consists of the following attributes: + +* `types.AttributeLockId` + * The value is the given lock ID. + +### `types.TypeEvtAddToConcentratedLiquiditySuperfluidPosition` + +This event is emitted in the message server after adding liquidity to an existing concentrated-liquidity superfluid position. + +It consists of the following attributes: + +* `types.AttributeKeySender` + * The value is the msg sender address. +* `types.AttributeKeyPoolId` + * The value is the concentrated pool ID. +* `types.AttributePositionId` + * The value is the previous position ID. +* `types.AttributeNewPositionId` + * The value is the new position ID created after adding liquidity. +* `types.AttributeAmount0` + * The value is the amount of token0 in the position. +* `types.AttributeAmount1` + * The value is the amount of token1 in the position. +* `types.AttributeConcentratedLockId` + * The value is the underlying concentrated lock ID. +* `types.AttributeLiquidity` + * The value is the resulting position liquidity. + +### `types.TypeEvtUnlockAndMigrateShares` + +This event is emitted when GAMM shares are unlocked and migrated to a full-range concentrated-liquidity position. + +### `types.TypeEvtCreateFullRangePositionAndSFDelegate` + +This event is emitted in the message server after creating a full-range concentrated-liquidity position and superfluid delegating it. + +It consists of the following attributes: + +* `types.AttributeLockId` + * The value is the created lock ID. +* `types.AttributePositionId` + * The value is the created full-range position ID. +* `types.AttributeValidator` + * The value is the validator address to delegate to. + ### `types.TypeEvtUnpoolId` This event is emitted in the message server `UnPoolWhitelistedPool` @@ -531,7 +680,7 @@ It consists of the following attributes: * `types.AttributeKeySender` * The value is the msg sender address. -* `types.AttributeLockId` +* `types.AttributeDenom` * The value is the pool lpShareDenom. * `types.AttributeNewLockIds` * The value is the exited lock ids in byte[]. @@ -694,11 +843,11 @@ the spot price at the last epoch boundary, and this is reset every epoch. We currently don't store historical multipliers, so the epoch parameter is kind of meaningless for now. -To calculate the staking power of the denom, one needs to multiply the -amount of the denom with `OsmoEquivalentMultipler` from this query with -the `MinimumRiskFactor` from the Params query endpoint. +To calculate the staking power of the denom, multiply the amount of the denom +by the `OsmoEquivalentMultiplier` from this query, then apply the risk discount +using the `MinimumRiskFactor` from the Params query endpoint. -`staking_power = amount * OsmoEquivalentMultipler * MinimumRiskFactor` +`staking_power = amount * OsmoEquivalentMultiplier * (1 - MinimumRiskFactor)` ### ConnectedIntermediaryAccount @@ -840,7 +989,7 @@ The superfluid module contains the following parameters: | Key | Type | Example | | ------------------- | ------- | ------- | -| minimum_risk_factor | decimal | 0.01 | +| minimum_risk_factor | decimal | 0.25 | ## Slashing @@ -982,6 +1131,5 @@ the `IntermediaryAccount` will be slashed by less than the ### GetTotalSyntheticAssetsLocked -TODO - expand on this Uses `lockup` accumulator to find total amount of -synthetic locks for a given `IntermediaryAccount` (Superfluid Asset + -Validator pair) +Uses the `lockup` accumulator to find the total amount of synthetic locks +for a given `IntermediaryAccount` (Superfluid Asset + Validator pair). diff --git a/docs/build/chain/tokenfactory/README.md b/docs/build/chain/tokenfactory/README.md index aa0ed684d..6a0c65e6c 100644 --- a/docs/build/chain/tokenfactory/README.md +++ b/docs/build/chain/tokenfactory/README.md @@ -54,13 +54,19 @@ message MsgMint { (gogoproto.moretags) = "yaml:\"amount\"", (gogoproto.nullable) = false ]; + string mintToAddress = 3 [ + (gogoproto.moretags) = "yaml:\"mint_to_address\"", + (amino.dont_omitempty) = true + ]; } ``` +When `mintToAddress` is left empty, the module mints to the sender. + **State Modifications:** - Safety check the following - - Check that the denom minting is created via `tokenfactory` module + - Check that the denom is created via the `tokenfactory` module - Check that the sender of the message is the admin of the denom - Mint designated amount of tokens for the denom via `bank` module @@ -76,13 +82,19 @@ message MsgBurn { (gogoproto.moretags) = "yaml:\"amount\"", (gogoproto.nullable) = false ]; + string burnFromAddress = 3 [ + (gogoproto.moretags) = "yaml:\"burn_from_address\"", + (amino.dont_omitempty) = true + ]; } ``` +When `burnFromAddress` is left empty, the module burns from the sender's own balance. + **State Modifications:** - Safety check the following - - Check that the denom minting is created via `tokenfactory` module + - Check that the denom is created via the `tokenfactory` module - Check that the sender of the message is the admin of the denom - Burn designated amount of tokens for the denom via `bank` module @@ -104,7 +116,7 @@ Setting of metadata for a specific denom is only allowed for the admin of the de It allows the overwriting of the denom metadata in the bank module. ```go -message MsgChangeAdmin { +message MsgSetDenomMetadata { string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; cosmos.bank.v1beta1.Metadata metadata = 2 [ (gogoproto.moretags) = "yaml:\"metadata\"", (gogoproto.nullable) = false ]; } @@ -113,7 +125,7 @@ message MsgChangeAdmin { **State Modifications:** - Check that sender of the message is the admin of denom -- Modify `AuthorityMetadata` state entry to change the admin of the denom +- Set/overwrite the bank-module `DenomMetadata` for the denom (via the bank keeper). ### SetBeforeSendHook diff --git a/docs/build/chain/twap/README.md b/docs/build/chain/twap/README.md index 63d411020..13b901ccb 100644 --- a/docs/build/chain/twap/README.md +++ b/docs/build/chain/twap/README.md @@ -3,14 +3,14 @@ The TWAP package is responsible for being able to serve TWAPs for every AMM pool. -A time weighted average price is a function that takes a sequence of `(time, price)` pairs, and returns a price representing an 'average' over the entire time period. The method of averaging can vary from the classic arithmetic mean, (such as geometric mean, harmonic mean), however we currently only implement arithmetic mean. +A time weighted average price is a function that takes a sequence of `(time, price)` pairs, and returns a price representing an 'average' over the entire time period. The method of averaging can vary (such as the arithmetic mean, geometric mean, or harmonic mean). We currently implement both the arithmetic mean and the geometric mean. ## Arithmetic mean TWAP Using the arithmetic mean, the TWAP of a sequence `(t_i, p_i)`, from `t_0` to `t_n`, indexed by time in ascending order, is: $$\frac{1}{t_n - t_0}\sum_{i=0}^{n-1} p_i (t_{i+1} - t_i)$$ Notice that the latest price `p_n` isn't used, as it has lasted for a time interval of `0` seconds in this range! -To illustrate with an example, given the sequence: `(0s, $$1), (4s, $$6), (5s, $1)`, the arithmetic mean TWAP is: +To illustrate with an example, given the sequence: `(0s, $1), (4s, $6), (5s, $1)`, the arithmetic mean TWAP is: $$\frac{\$1 * (4s - 0s) + \$6 * (5s - 4s)}{5s - 0s} = \frac{\$10}{5} = \$2$$ ## Computation via accumulators method @@ -57,12 +57,26 @@ The primary intended API is `GetArithmeticTwap`, which is documented below, and func (k Keeper) GetArithmeticTwap(ctx sdk.Context, poolId uint64, baseAssetDenom string, quoteAssetDenom string, - startTime time.Time, endTime time.Time) (sdk.Dec, error) { ... } + startTime time.Time, endTime time.Time) (osmomath.Dec, error) { ... } ``` There are convenience methods for `GetArithmeticTwapToNow` which sets `endTime = ctx.BlockTime()`, and has minor gas reduction. For users who need TWAPs outside the 48 hours stored in the state machine, you can get the latest accumulation store record from `GetBeginBlockAccumulatorRecord`. +The module also exposes a geometric mean variant with the same shape and a similar cosmwasm binding: + +```go +// GetGeometricTwap returns a geometric time weighted average price. +// It takes the same arguments and obeys the same constraints as GetArithmeticTwap, +// but computes the average using the geometric mean instead of the arithmetic mean. +func (k Keeper) GetGeometricTwap(ctx sdk.Context, + poolId uint64, + baseAssetDenom string, quoteAssetDenom string, + startTime time.Time, endTime time.Time) (osmomath.Dec, error) { ... } +``` + +As with the arithmetic variant, there is a `GetGeometricTwapToNow` convenience method which sets `endTime = ctx.BlockTime()`. + ## Code layout **api.go** is the main file you should look at as a user of this module. @@ -86,7 +100,7 @@ Because Osmosis supports multi-asset pools, a complicating factor is that we hav For every pool, at a given point in time, we make one twap record entry per unique pair of denoms in the pool. If a pool has `k` denoms, the number of unique pairs is `k * (k - 1) / 2`. All public API's for the module will sort the input denoms to the canonical representation, so the caller does not need to worry about this. (The canonical representation is the denoms in lexicographical order) -Each twap record stores [(source)](https://github.com/osmosis-labs/osmosis/tree/main/proto/osmosis/gamm/twap): +Each twap record stores [(source)](https://github.com/osmosis-labs/osmosis/tree/main/proto/osmosis/twap/v1beta1): * last spot price of base asset A in terms of quote asset B * last spot price of base asset B in terms of quote asset A @@ -130,6 +144,8 @@ Therefore, at the end of an epoch records younger than 48 hours before the curre ## Testing Methodology +> This section documents the original pre-release test plan for the twap module and is retained for historical context. The unchecked items below reflect the plan as written before launch (the migration anchor references the v11 upgrade) and are not a live status tracker. + The pre-release testing methodology planned for the twap module is: - [ ] Using table driven unit tests to test all foreseen states of the module diff --git a/docs/build/chain/txfees/README.md b/docs/build/chain/txfees/README.md index 411d5bb97..f62ee6e46 100644 --- a/docs/build/chain/txfees/README.md +++ b/docs/build/chain/txfees/README.md @@ -3,7 +3,7 @@ The txfees modules allows nodes to easily support many tokens for usage as txfees, while letting node operators only specify their tx fee parameters for a single "base" asset. This is done by having this module maintain an allow-list of token denoms which can be used as tx fees, each with some associated metadata. Then this metadata is used in tandem with a "Spot Price Calculator" provided to the module, to convert the provided tx fees into their equivalent value in the base denomination. -Currently the only supported metadata & spot price calculator is using a GAMM pool ID & the GAMM keeper. +Each fee token is associated with a pool ID, and the spot price is calculated through the poolmanager's `RouteCalculateSpotPrice`, which abstracts over the underlying pool type rather than depending on the GAMM keeper directly. ## State Changes @@ -13,22 +13,21 @@ Currently the only supported metadata & spot price calculator is using a GAMM po not the base denom will be collected in a separate module account to be batched and swapped into the base denom at the end of each epoch. -* Adds a new SDK message for creating governance proposals for adding new TxFee denoms. +* Fee tokens are added or removed with the `MsgSetFeeTokens` message, which is gated to the addresses in the `WhitelistedFeeTokenSetters` parameter. ## Local Mempool Filters Added * If you specify a min-tx-fee in the $BASEDENOM then * Your node will allow any tx w/ tx fee in the whitelist of fees, and a sufficient osmo-equivalent price to enter your mempool * The osmo-equivalent price for determining sufficiency is rechecked after every block. (During the mempools RecheckTx) - * TODO: further consider if we want to take this tradeoff. Allows someone who manipulates price for one block to flush txs using that asset as fee from most of the networks' mempools. + * This rechecking is a deliberate tradeoff: it allows someone who manipulates price for one block to flush txs using that asset as fee from most of the networks' mempools. * The simple alternative is only check fee equivalency at a txs entry into the mempool, which allows someone to manipulate price down to have many txs enter the chain at low cost. - * Another alternative is to use TWAP instead of Spot Price once it is available onchain * The former concern isn't very worrisome as long as some nodes have 0 min tx fees. * A separate min-gas-fee can be set on every node for arbitrage txs. Methods of detecting an arb tx atm * does start token of a swap = final token of swap (definitionally correct) * does it have multiple swap messages, with different tx ins. If so, we assume its an arb. * This has false positives, but is intended to avoid the obvious solution of splitting an arb into multiple messages. - * We record all denoms seen across all swaps, and see if any duplicates. (TODO) + * We record all denoms seen across all swaps, and see if any duplicates. * Contains both JoinPool and ExitPool messages in one tx. * Has some false positives. * These false positives seem like they primarily will get hit during batching of many distinct operations, not really in one atomic action. @@ -68,6 +67,6 @@ fee-tokens ## Future directions -* Want to add in a system to add in general "tx fee credits" for different on-chain usages +* Want to add in a system to add in general "tx fee credits" for different onchain usages * e.g. making 0 fee txs under certain usecases * If other chains would like to use this, we should brainstorm mechanisms for extending the metadata proto fields \ No newline at end of file diff --git a/docs/build/chain/valset-pref/README.md b/docs/build/chain/valset-pref/README.md index e29dd4d74..e7fb6748e 100644 --- a/docs/build/chain/valset-pref/README.md +++ b/docs/build/chain/valset-pref/README.md @@ -6,7 +6,7 @@ Validator-Set preference is a new module which gives users and contracts a better UX for staking to a set of validators. For example: a one click button that delegates to multiple validators. Then the user can set (or realistically a frontend provides) a list of recommended defaults (Ex: active governors, relayers, core stack contributors etc). -Currently this can be done on-chain with frontends, but having a preference list stored locally +Currently this can be done onchain with frontends, but having a preference list stored locally eases frontend code burden. ## Design diff --git a/docs/build/cosmwasm/beaker/README.md b/docs/build/cosmwasm/beaker/README.md index 8f661591d..56c025762 100644 --- a/docs/build/cosmwasm/beaker/README.md +++ b/docs/build/cosmwasm/beaker/README.md @@ -4,21 +4,16 @@ description: Scaffold, deploy, and interact with contracts using Beaker. # Beaker +:::warning Beaker is no longer actively maintained +Beaker's last release was v0.1.8 (November 2023). For new contracts, use [cw-orchestrator](/build/cosmwasm/cw-orch) with the [Quickstart](/build/cosmwasm/quickstart). These pages remain as a reference for projects already built on Beaker. +::: +

- + Beaker logo

-

- - - - - - -

- [Beaker](https://github.com/osmosis-labs/beaker) makes it easy to scaffold a new cosmwasm app, with all of the dependencies for osmosis hooked up, interactive console, and a sample front-end at the ready. --- @@ -161,7 +156,7 @@ template_repo = "https://github.com/osmosis-labs/cw-tpl-osmosis.git" ### Deploy contract on LocalOsmosis -LocalOsmosis, as its name suggest, is Osmosis for local development. In the upcoming release, Beaker will have more complete integration with LocalOsmosis, it has to be installed and run separately. +LocalOsmosis, as its name suggests, is Osmosis for local development. It has to be installed and run separately. You can install from source by following the instruction at [osmosis-labs/LocalOsmosis](https://github.com/osmosis-labs/LocalOsmosis), or use the official installer and select option 3: @@ -229,10 +224,10 @@ To create the contract entrypoint for migration, first, define `MigrateMsg` in ` pub struct MigrateMsg {} ``` -With MigrateMsg defined we need to update `contract.rs`. First update the import from `create::msg` to include `MigrateMsg`: +With MigrateMsg defined we need to update `contract.rs`. First update the import from `crate::msg` to include `MigrateMsg`: ```rust -use create::msg::{CountResponse, ExecuteMsg, InstantiateMsg, QueryMsg, MigrateMsg}; +use crate::msg::{CountResponse, ExecuteMsg, InstantiateMsg, QueryMsg, MigrateMsg}; ``` ```rust @@ -346,8 +341,8 @@ await contract.counter.query({ get_count: {} }); You can find available methods for the aforementioned instances here: -- [Account](console/classes//Account.md#methods-1) -- [Contract](./console/classes//Contract.md#methods-1) +- [Account](./console/classes/Account.md#methods-1) +- [Contract](./console/classes/Contract.md#methods-1) You can remove `contract` and/or `account` namespace by changing config. @@ -366,7 +361,7 @@ await counter.query({ get_count: {} }); -With the Typescript SDK which was previously mentioned, it is used to extend the `Contract` instance with method generated ftom execute and query messages. For example: +With the Typescript SDK which was previously mentioned, it is used to extend the `Contract` instance with methods generated from execute and query messages. For example: ```js await counter.getCount() @@ -379,13 +374,13 @@ await sc.getCount() With this, it's more convenient than the previous interaction method since you can use tab completion for the methods as well. -Beaker console is also allowed to deploy contract, so that you don't another terminal tab to do so. +Beaker console is also allowed to deploy contracts, so that you don't need another terminal tab to do so. ```js .deploy counter -- --signer-account test1 --raw '{ "count": 999 }' ``` -`.build`, `.storeCode`, `.instantiate` commands are also available and has the same options as Beaker cli command, except that `--no-wasm-opt` are in by default since it is being intended to use in the development phase. +`.build`, `.storeCode`, `.instantiate` commands are also available and have the same options as the Beaker CLI commands, except that `--no-wasm-opt` is on by default since it is intended for use in the development phase. `.help` to see all available commands. diff --git a/docs/build/cosmwasm/beaker/commands/README.md b/docs/build/cosmwasm/beaker/commands/README.md index 5d3318f99..2dc58096d 100644 --- a/docs/build/cosmwasm/beaker/commands/README.md +++ b/docs/build/cosmwasm/beaker/commands/README.md @@ -4,7 +4,7 @@ CosmWasm development tooling -Version: 0.0.6 +Version: 0.1.8 (last release, November 2023) Arguments: diff --git a/docs/build/cosmwasm/beaker/commands/beaker_wasm.md b/docs/build/cosmwasm/beaker/commands/beaker_wasm.md index a0855e206..c13990c47 100644 --- a/docs/build/cosmwasm/beaker/commands/beaker_wasm.md +++ b/docs/build/cosmwasm/beaker/commands/beaker_wasm.md @@ -88,13 +88,13 @@ Arguments: * ` `Name of the contract to store -* `--schema-gen-cmd `: Sschema generation command, default: `cargo run -p {contract_name} --example schema` +* `--schema-gen-cmd `: Schema generation command, default: `cargo run -p {contract_name} --example schema` * `--schema-dir `: Directory of input schema for ts generation * `--out-dir `: Code output directory, ignore remaining ts build process if custom out_dir is specified -* `--node-package-manager `: Code output directory (default: `yarn`) +* `--node-package-manager `: Node package manager to use (default: `yarn`) --- @@ -166,7 +166,7 @@ Arguments: ### `beaker wasm instantiate` -Instanitate .wasm stored on chain +Instantiate .wasm stored on chain Arguments: @@ -208,7 +208,7 @@ Arguments: ### `beaker wasm migrate` -Migrated instanitate contract to use other code stored on chain +Migrate an instantiated contract to use other code stored on chain Arguments: diff --git a/docs/build/cosmwasm/cosmwasm-beaker.md b/docs/build/cosmwasm/cosmwasm-beaker.md index 492878675..6bf17df6a 100644 --- a/docs/build/cosmwasm/cosmwasm-beaker.md +++ b/docs/build/cosmwasm/cosmwasm-beaker.md @@ -98,7 +98,7 @@ deposit: 500000000uosmo code: repo: https://github.com/osmosis-labs/beaker/ rust_flags: -C link-arg=-s - roptimizer: workspace-optimizer:0.12.6 + optimizer: workspace-optimizer:0.12.6 ``` ```sh @@ -166,12 +166,12 @@ Great! Your proposal should have passed now! ### Signers -In the examples above we used the test1 account to sign transactions. However, Bekaer supports 3 options for signing transactions as shown on the official [README](https://github.com/osmosis-labs/beaker#Signers). +In the examples above we used the test1 account to sign transactions. However, Beaker supports 3 options for signing transactions as shown on the official [README](https://github.com/osmosis-labs/beaker#Signers). -- `--signer-account` input of this option refer to the accounts defined in the [config file](./beaker/config/global), which is not encrypted, so it should be used only for testing +- `--signer-account` input of this option refer to the accounts defined in the [config file](./beaker/config/global.md), which is not encrypted, so it should be used only for testing - `--signer-mnemonic` input of this option is the raw mnemonic string to construct a signer - `--signer-private-key` input of this option is the same as `--signer-mnemonic` except it expects base64 encoded private key -- `--signer-keyring` use the OS secure store as backend to securely store your key. To manage them, you can find more information [here](./beaker/commands/beaker_key). +- `--signer-keyring` use the OS secure store as backend to securely store your key. To manage them, you can find more information [here](./beaker/commands/beaker_key.md). ### Using the OS keyring Let's dive a little deeper on how to use the OS keyring in order to sign a transaction with your OS keyring. diff --git a/docs/build/cosmwasm/cosmwasm-deployment.md b/docs/build/cosmwasm/cosmwasm-deployment.md index 00e0376a8..7d2059c9e 100644 --- a/docs/build/cosmwasm/cosmwasm-deployment.md +++ b/docs/build/cosmwasm/cosmwasm-deployment.md @@ -23,7 +23,7 @@ The following is a quick guide that shows the basics of deploying a contract to - Contract explorer :::tip -Please note this is a detailed guide on how to deploy via `osmosisd`, it also covers additional tooling and useful tips. You can also deploy to testnet with [Beaker](./cosmwasm-beaker.md) with a couple of commands. +This is a detailed guide on how to deploy via `osmosisd`, covering additional tooling and useful tips. For the recommended scripted workflow, see [cw-orchestrator](/build/cosmwasm/cw-orch) and the [Quickstart](/build/cosmwasm/quickstart). ::: @@ -43,7 +43,7 @@ Then run the following commands: # 1. Set 'stable' as the default release channel: rustup default stable cargo version -# If this is lower than 1.50.0+, update +# Update to a recent stable toolchain (CosmWasm and the optimizer track current Rust) rustup update stable # 2. Add WASM as the compilation target: @@ -64,7 +64,7 @@ Run the following and choose option #2 (Client Node) and #2 (Testnet) in order. ```bash curl -sL https://get.osmosis.zone/install > i.py && python3 i.py ``` -Now you have successfully completed setting up an Osmosis client node in Testnet. In order to use `osmosisd` from the cli, either reload your terminal or refresh your profile with : `‘source ~/.profile’` +Now you have successfully completed setting up an Osmosis client node in Testnet. In order to use `osmosisd` from the cli, either reload your terminal or refresh your profile with `source ~/.profile` ### Setup the Client @@ -147,7 +147,7 @@ cargo wasm wasm = "build --release --target wasm32-unknown-unknown" ``` - So when we run the `cargo wasm` command, the `cargo build --release —-target wasm32-unknown-unknown` command is executed according to the option in the config file above. + So when we run the `cargo wasm` command, the `cargo build --release --target wasm32-unknown-unknown` command is executed according to the option in the config file above. After this compiles, it should produce a file in `target/wasm32-unknown-unknown/release/cw_tpl_osmosis.wasm`. If you check the size of the file by using the `ls -lh` command, it shows around `1.8M`. This is a release build, but not stripped of all unneeded code. To produce a much smaller version, you can run this which tells the compiler to strip all unused code out: @@ -194,7 +194,7 @@ RES=$(osmosisd query tx "$TXHASH" --output json) - `--gas-adjustment` : adjustment factor to be multiplied against the estimate returned by the tx simulation. - `-y` : to skip tx broadcasting prompt confirmation. - `--output` : output format. -- `-b sync` : broadcast the transaction synchronously and return immediately with the txhash. The `block` mode used in older Cosmos SDK versions is no longer supported — query the tx by hash after the next block to fetch the result. +- `-b sync` : broadcast the transaction synchronously and return immediately with the txhash. The `block` mode used in older Cosmos SDK versions is no longer supported, so query the tx by hash after the next block to fetch the result. ![](https://user-images.githubusercontent.com/70956926/172293654-7beba11b-ce5f-4979-94e2-19156c6e5b27.png) @@ -216,7 +216,7 @@ Run the following command to set the `CODE_ID` as a variable: ```bash # get CODE_ID -CODE_ID=$(echo $RES | jq -r '.logs[0].events[-1].attributes[0].value') +CODE_ID=$(echo $RES | jq -r '.events[] | select(.type=="store_code") | .attributes[] | select(.key=="code_id") | .value') echo $CODE_ID ``` diff --git a/docs/build/cosmwasm/cosmwasm-verify-contract.md b/docs/build/cosmwasm/cosmwasm-verify-contract.md index e08bca1a5..dcc308733 100644 --- a/docs/build/cosmwasm/cosmwasm-verify-contract.md +++ b/docs/build/cosmwasm/cosmwasm-verify-contract.md @@ -9,7 +9,7 @@ The following are the steps needed to verify any contract from the chain. In thi ### Create new contract -Follow [this guide](./cosmwasm-beaker) to create a new contract with Beaker. +Follow the [Quickstart](/build/cosmwasm/quickstart) to scaffold and deploy a contract. Output: diff --git a/docs/build/cosmwasm/cw-orch.md b/docs/build/cosmwasm/cw-orch.md index 8e7debb8b..ddb86ac0c 100644 --- a/docs/build/cosmwasm/cw-orch.md +++ b/docs/build/cosmwasm/cw-orch.md @@ -7,21 +7,21 @@ sidebar_position: 8 ## Introduction -cw-orchestrator is the most advanced scripting, testing, and deployment framework for CosmWasm smart-contracts. It makes it easy to write cross-environment compatible code for [cw-multi-test](https://github.com/CosmWasm/cw-multi-test), [Osmosis Test Tube](https://github.com/osmosis-labs/test-tube), [Starship](https://github.com/cosmology-tech/starship) (alpha), and **live networks**, significantly reducing code duplication and test-writing time. +cw-orchestrator is the most advanced scripting, testing, and deployment framework for CosmWasm smart-contracts. It makes it easy to write cross-environment compatible code for [cw-multi-test](https://github.com/CosmWasm/cw-multi-test), [Osmosis Test Tube](https://github.com/osmosis-labs/test-tube), [Starship](https://github.com/hyperweb-io/starship) (alpha), and **live networks**, significantly reducing code duplication and test-writing time. Get ready to change the way you interact with contracts and simplify your smart-contracts journey. The following steps will allow you to integrate `cw-orch` and write clean code such as: ```rust counter.upload()?; -counter.instantiate(&InstantiateMsg { count: 0 }, None, None)?; +counter.instantiate(&InstantiateMsg { count: 0 }, None, &[])?; counter.increment()?; let count = counter.get_count()?; assert_eq!(count.count, 1); ``` -In this quick-start guide, we will review the necessary steps in order to integrate [`cw-orch`](https://github.com/AbstractSDK/cw-orchestrator) into a simple contract create. [We review integration of rust-workspaces (multiple contracts) at the end of this page](#integration-in-a-workspace). +In this quick-start guide, we will review the necessary steps in order to integrate [`cw-orch`](https://github.com/AbstractSDK/cw-orchestrator) into a simple contract crate. [We review integration of rust-workspaces (multiple contracts) at the end of this page](#integration-in-a-workspace). > **NOTE**: *Quicker than the quick start* > @@ -41,7 +41,7 @@ In this quick-start guide, we will review the necessary steps in order to integr - [Using the integration](#using-the-integration) - [Integration in a workspace](#integration-in-a-workspace) - [Handling dependencies and features](#handling-dependencies-and-features) - - [Creating an interface create](#creating-an-interface-create) + - [Creating an interface crate](#creating-an-interface-crate) - [Integrating single contracts](#integrating-single-contracts) - [More examples and scripts](#more-examples-and-scripts) @@ -94,7 +94,7 @@ Then, inside that `interface.rs` file, you can define the interface for your con ```rust use cw_orch::{interface, prelude::*}; -use create::msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg}; +use crate::msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg}; pub const CONTRACT_ID: &str = "counter_contract"; @@ -112,11 +112,11 @@ impl Uploadable for CounterContract { fn wrapper(&self) -> Box> { Box::new( ContractWrapper::new_with_empty( - create::contract::execute, - create::contract::instantiate, - create::contract::query, + crate::contract::execute, + crate::contract::instantiate, + crate::contract::query, ) - .with_migrate(create::contract::migrate), + .with_migrate(crate::contract::migrate), ) } } @@ -129,7 +129,7 @@ Learn more about the content of the interface creation specifics in the [`cw-orc > > ```rust > #[cfg(feature = "interface")] -> pub use create::interface::CounterContract; +> pub use crate::interface::CounterContract; > ``` ### Interaction helpers @@ -177,14 +177,14 @@ Find out more about the interaction helpers in the [`cw-orch` documentation](htt > > ```rust > #[cfg(feature = "interface")] -> pub use create::msg::{ExecuteMsgFns as CounterExecuteMsgFns, QueryMsgFns as CounterQueryMsgFns}; +> pub use crate::msg::{ExecuteMsgFns as CounterExecuteMsgFns, QueryMsgFns as CounterQueryMsgFns}; > ``` ### Using the integration Now that all the setup is done, you can use your contract in tests, integration-tests or scripts. -Start by importing your create, with the `interface` feature enabled. Depending on your use-case this will be in `[dependencies]` or `[dev-dependencies]`: +Start by importing your crate, with the `interface` feature enabled. Depending on your use-case this will be in `[dependencies]` or `[dev-dependencies]`: ```toml counter-contract = { path = "../counter-contract", features = ["interface"] } @@ -206,7 +206,7 @@ pub fn main() -> anyhow::Result<()> { pretty_env_logger::init(); // Used to log contract and chain interactions let rt = Runtime::new()?; - let network = networks::LOCAL_JUNO; + let network = networks::LOCAL_OSMOSIS; let chain = DaemonBuilder::default() .handle(rt.handle()) .chain(network) @@ -216,7 +216,7 @@ pub fn main() -> anyhow::Result<()> { let counter = CounterContract::new(chain); counter.upload()?; - counter.instantiate(&InstantiateMsg { count: 0 }, None, None)?; + counter.instantiate(&InstantiateMsg { count: 0 }, None, &[])?; counter.increment()?; @@ -245,9 +245,9 @@ Refer above to [Adding `cw-orch` to your `Cargo.toml` file](#adding-cw-orch-to-y For instance, for the `cw20_base` contract, you need to execute those 2 steps on the `cw20-base` contract (where the `QueryMsg` are defined) as well as on the `cw20` package (where the `ExecuteMsg` are defined). -### Creating an interface create +### Creating an interface crate -When using a workspace, we advise you to create a new create inside your workspace for defining your contract's interfaces. In order to do that, use: +When using a workspace, we advise you to create a new crate inside your workspace for defining your contract's interfaces. In order to do that, use: ```shell cargo new interface --lib @@ -261,7 +261,7 @@ Add the interface package to your workspace `Cargo.toml` file members = ["packages/*", "contracts/*", "interface"] ``` -Inside this `interface` create, we advise to integrate all your contracts 1 by 1 in separate files. Here is the structure of the `cw-plus` integration for reference: +Inside this `interface` crate, we advise to integrate all your contracts 1 by 1 in separate files. Here is the structure of the `cw-plus` integration for reference: ```path interface (interface collection) diff --git a/docs/build/cosmwasm/index.mdx b/docs/build/cosmwasm/index.mdx index dc5664cfa..9fb19f840 100644 --- a/docs/build/cosmwasm/index.mdx +++ b/docs/build/cosmwasm/index.mdx @@ -9,7 +9,7 @@ import DocCardList from '@theme/DocCardList'; CosmWasm lets you write smart contracts in Rust and run them on Osmosis. This section covers the full contract lifecycle: scaffolding a project, building and testing, deploying to a local or test network, verifying a deployed contract, and calling contracts from your application. -**Beaker** is the recommended starting point, a scaffolding tool that wires up contract dependencies, an interactive console, and a sample frontend. From there, **CosmWasm & LocalOsmosis** covers developing against a local chain, and the **testnet deployment** and **CosmWasm & Beaker** guides walk through deploying to a public testnet, with **Submit a CosmWasm Governance Proposal** for the gov-gated store step. **Verifying Smart Contracts** covers reproducible builds, **cw-orchestrator** handles scripting and testing across environments, and the **JavaScript** guide shows how to call deployed contracts from a JavaScript runtime. +The **Quickstart** is the recommended starting point: it scaffolds a contract with the official CosmWasm template and uses **cw-orchestrator** to build, deploy, and test across environments. From there, **CosmWasm & LocalOsmosis** covers developing against a local chain, and the **testnet deployment** guide walks through deploying to a public testnet, with **Submit a CosmWasm Governance Proposal** for the gov-gated store step. **Verifying Smart Contracts** covers reproducible builds, and the **JavaScript** guide shows how to call deployed contracts from a JavaScript runtime. The **CosmWasm & Beaker** pages remain for projects already using Beaker, which is no longer actively maintained. If you are building UIs or SDK integrations rather than contracts, see Frontend. diff --git a/docs/build/cosmwasm/javascript.md b/docs/build/cosmwasm/javascript.md index 79713f4ba..26399ee66 100644 --- a/docs/build/cosmwasm/javascript.md +++ b/docs/build/cosmwasm/javascript.md @@ -27,14 +27,12 @@ npm i cosmwasm Open the package.json file in a code editor and add -```json= -"type": "module",. - - { - // ... - "type": "module", - // ... - } +```json +{ + // ... + "type": "module" + // ... +} ``` Create a new index.ts file @@ -45,7 +43,7 @@ touch index.ts The class CosmWasmClient is exported from the CosmJS package @cosmjs/cosmwasm-stargate. Learn more in the [official docs](https://cosmwasm.github.io/CosmWasmJS/clients/reading/CosmWasmClient.html). -```javascript= +```javascript import { CosmWasmClient } from "cosmwasm"; // This is your rpc endpoint @@ -59,14 +57,14 @@ async function main() { main(); ``` -:: tip -You can also connect to the mainnet by replacing rpcEndpoint to https://rpc.osmosis.zone/ -:: +:::tip +You can also connect to the mainnet by replacing rpcEndpoint with https://rpc.osmosis.zone/ +::: ## Run it ``` -npm index.js +node index.js ``` You should see something like: @@ -76,7 +74,7 @@ You should see something like: As documented on the [official docs](https://cosmwasm.github.io/CosmWasmJS/clients/reading/CosmWasmClient.html#available-methods). -```javascript= +```javascript async function moreExamples() { const client = await CosmWasmClient.connect(rpcEndpoint); const chainId = await client.getChainId() @@ -173,7 +171,7 @@ node index.js ``` The output should look like this: -![](contract_details.png) +![](./contract_details.png) ## Get the count from the contract diff --git a/docs/build/cosmwasm/localosmosis.md b/docs/build/cosmwasm/localosmosis.md index 04051adf3..67ca9604b 100644 --- a/docs/build/cosmwasm/localosmosis.md +++ b/docs/build/cosmwasm/localosmosis.md @@ -6,11 +6,11 @@ sidebar_position: 3 # CosmWasm & LocalOsmosis -:::tip -You can now deploy contracts to LocalOsmosis with [Beaker](https://github.com/osmosis-labs/beaker). The official tooling to deploy Osmosis Smartcontracts. +:::tip +For new contracts, the recommended workflow is [cw-orchestrator](/build/cosmwasm/cw-orch) with the [Quickstart](/build/cosmwasm/quickstart). This page shows the underlying manual steps, which use Beaker (no longer actively maintained) and `osmosisd` directly. ::: -The following is detailed guide that shows the basics of manually deploying a contract to a Osmosis local environment. It covers: +The following is a detailed guide that shows the basics of manually deploying a contract to an Osmosis local environment. It covers: - Initial Setup - Rust @@ -75,7 +75,7 @@ Install the following packages to generate the contract: ```bash cargo install cargo-generate --features vendored-openssl -cargo install cargo-run-scrip +cargo install cargo-run-script ``` #### Beaker @@ -148,7 +148,7 @@ This produces a file about 149kB. We will do further optimisation below. ### Optimized Compilation -To reduce gas costs, the binary size should be as small as possible. This will result in a less costly deployment, and lower fees on every interaction. Luckily, there is tooling to help with this. You can optimize production code using rust-optimizer. rust-optimizer produces reproducible builds of CosmWasm smart contracts. This means third parties can verify the contract is actually the claimed code. +To reduce gas costs, the binary size should be as small as possible. This will result in a less costly deployment, and lower fees on every interaction. Luckily, there is tooling to help with this. You can optimize production code using the CosmWasm optimizer (`cosmwasm/optimizer`), which produces reproducible builds of CosmWasm smart contracts. This means third parties can verify the contract is actually the claimed code. ``` @@ -159,7 +159,7 @@ sudo docker run --rm -v "$(pwd)":/code \ ``` -Binary will be at artifacts/osmosis_cw_tpl.wasm folder and its size will be 138k +Binary will be at artifacts/cw_tpl_osmosis.wasm and its size will be 138k ### Created a local key Create a key using one of the seeds provided in localOsmosis. @@ -179,7 +179,7 @@ You can deploy the contract to localOsmosis or a testnet. In this example we wi ``` cd artifacts -osmosisd tx wasm store cw_tpl_osmosis.wasm --from --chain-id= --gas-prices 0.05uosmo --gas auto --gas-adjustment 1.3 -b block -y +osmosisd tx wasm store cw_tpl_osmosis.wasm --from --chain-id= --gas-prices 0.05uosmo --gas auto --gas-adjustment 1.3 -b sync -y ``` `` = Name of your local key. @@ -193,8 +193,8 @@ Save the CODE_ID from the output of the command above as a local variable `CODE_ Instead of looking for the code_id the command above, you can also run the following command to set the CODE_ID as a variable. ``` -TX=$(osmosisd tx wasm store cw_tpl_osmosis.wasm --from --chain-id= --gas-prices 0.05uosmo --gas auto --gas-adjustment 1.3 -b block --output json -y | jq -r '.txhash') -CODE_ID=$(osmosisd query tx $TX --output json | jq -r '.logs[0].events[-1].attributes[0].value') +TX=$(osmosisd tx wasm store cw_tpl_osmosis.wasm --from --chain-id= --gas-prices 0.05uosmo --gas auto --gas-adjustment 1.3 -b sync --output json -y | jq -r '.txhash') +CODE_ID=$(osmosisd query tx $TX --output json | jq -r '.events[] | select(.type=="store_code") | .attributes[] | select(.key=="code_id") | .value') echo "Your contract code_id is $CODE_ID" ``` @@ -205,13 +205,13 @@ If this is a brand new localOsmosis instance it should be `1` ``` INITIAL_STATE='{"count":100}' -osmosisd tx wasm instantiate $CODE_ID $INITIAL_STATE --amount 50000uosmo --label "Counter Contract" --from --chain-id --gas-prices 0.05uosmo --gas auto --gas-adjustment 1.3 -b block -y --no-admin +osmosisd tx wasm instantiate $CODE_ID $INITIAL_STATE --amount 50000uosmo --label "Counter Contract" --from --chain-id --gas-prices 0.05uosmo --gas auto --gas-adjustment 1.3 -b sync -y --no-admin ``` Example ``` INITIAL_STATE='{"count":100}' -osmosisd tx wasm instantiate $CODE_ID $INITIAL_STATE --amount 50000uosmo --label "Counter Contract" --from c1 --chain-id localosmosis --gas-prices 0.05uosmo --gas auto --gas-adjustment 1.3 -b block -y --no-admin +osmosisd tx wasm instantiate $CODE_ID $INITIAL_STATE --amount 50000uosmo --label "Counter Contract" --from c1 --chain-id localosmosis --gas-prices 0.05uosmo --gas auto --gas-adjustment 1.3 -b sync -y --no-admin ``` ### Get contract address diff --git a/docs/build/cosmwasm/quickstart.md b/docs/build/cosmwasm/quickstart.md new file mode 100644 index 000000000..dbd85f058 --- /dev/null +++ b/docs/build/cosmwasm/quickstart.md @@ -0,0 +1,60 @@ +--- +title: Quickstart +description: Scaffold, build, and deploy your first CosmWasm contract on Osmosis. +sidebar_position: 1 +--- + +# CosmWasm Quickstart + +The fastest path from nothing to a deployed contract on Osmosis. Each step links to the page with the full detail; this page is the ordered happy path. + +## 1. Scaffold a contract + +Use `cargo generate` with the official CosmWasm template to create a working contract and build system: + +```bash +cargo install cargo-generate --features vendored-openssl +cargo generate --git https://github.com/CosmWasm/cw-template.git --name my-contract +cd my-contract +``` + +This gives you a cargo project with a sample contract (the standard `counter`), an entry-point layout, and a build setup you can customize. + +## 2. Add cw-orchestrator + +[cw-orchestrator](/build/cosmwasm/cw-orch) is the actively maintained tool for building, deploying, and testing CosmWasm contracts, and the recommended path on Osmosis. Add it to the contract crate as an optional dependency: + +```bash +cargo add --optional cw-orch +``` + +Adding it as optional and enabling it behind an `interface` feature flag keeps `cw-orch` out of the compiled wasm artifact. You then define a typed interface for the contract and use it to write deploy and test scripts that run unchanged against a local chain, a testnet, or mainnet. See [Scripts and Tests with cw-orchestrator](/build/cosmwasm/cw-orch) for the feature setup, the interface macro, and the full workflow. + +## 3. Build and test locally + +Develop against a local chain. Spin up [LocalOsmosis](/build/cosmwasm/localosmosis): + +```bash +make localnet-start # from a checkout of the osmosis repo +``` + +Then build, upload, and instantiate the contract against it from a cw-orch script: + +```rust +let counter = CounterContract::new(chain); +counter.upload()?; +counter.instantiate(&InstantiateMsg { count: 0 }, None, &[])?; +``` + +cw-orchestrator also runs the same scripts against [cw-multi-test](https://github.com/CosmWasm/cw-multi-test) and [Osmosis Test Tube](https://github.com/osmosis-labs/test-tube) for fast unit and integration tests with no node running. See [CosmWasm & LocalOsmosis](/build/cosmwasm/localosmosis) for the local accounts and full workflow. + +## 4. Deploy to testnet + +When the contract works locally, point the same cw-orch script at a public testnet, or upload with `osmosisd` directly (see [testnet deployment](/build/cosmwasm/cosmwasm-deployment)). Storing code on a network where governance gates it goes through a [governance proposal](/build/cosmwasm/submit-wasm-proposal). + +> Beaker was a popular all-in-one scaffolding and deployment tool, but it is no longer actively maintained (last release 2023). The [Beaker pages](/build/cosmwasm/beaker) remain for existing projects; new contracts should use the workflow above. + +## Next steps + +- **Verify** your deployed contract reproducibly: [Verifying Smart Contracts](/build/cosmwasm/cosmwasm-verify-contract). +- **Call the contract from an app:** the [JavaScript guide](/build/cosmwasm/javascript), or build a full frontend with [Frontend & SDKs](/build/frontend). diff --git a/docs/build/cosmwasm/submit-wasm-proposal.md b/docs/build/cosmwasm/submit-wasm-proposal.md index bf519979b..bf25bd9bc 100644 --- a/docs/build/cosmwasm/submit-wasm-proposal.md +++ b/docs/build/cosmwasm/submit-wasm-proposal.md @@ -20,23 +20,22 @@ curl -sL https://get.osmosis.zone/install > i.py && python3 i.py ### Start localOsmosis -Inside a separate bash window start your localOsmosis which was installed in ~/localosmosis +Inside a separate bash window, start LocalOsmosis from a checkout of the Osmosis repo: ``` -cd ~/localosmosis -docker-compose up - +cd ~/osmosis +make localnet-start ``` You will start seeing LocalOsmosis block activity in your terminal. Keep LocalOsmosis running while you perform the next steps in a new terminal window. :::tip -If you had previously installed localOsmosis, it's a good idea to start fresh and delete ~/localosmosis `rm -rf ~/localosmosis` before installing it again. +See [CosmWasm & LocalOsmosis](/build/cosmwasm/localosmosis) for the full local setup, including the automatic installer option. ::: ## Download sample contract ``` -curl -s -L -O https://github.com/CosmWasm/cw-plus/releases/download/v0.12.1/cw20_base.wasm +curl -s -L -O https://github.com/CosmWasm/cw-plus/releases/download/v1.1.2/cw20_base.wasm ``` ## Define variables @@ -62,10 +61,13 @@ VAL=$(osmosisd keys show -a validator --keyring-backend test) ## Submit proposal +Storing code on a permissioned network goes through `x/wasm`'s own governance proposal command, `tx wasm submit-proposal wasm-store` (the older `tx gov submit-proposal wasm-store` form, and the `--description` flag, were removed in newer SDK/wasmd versions; metadata is now `--title` plus `--summary`, and the stored message's `--authority` is the gov module address): + ``` -osmosisd tx gov submit-proposal wasm-store $CONTRACT.wasm --title "Add $CONTRACT" \ - --description "Let's upload this contract" --run-as $VAL \ - --from validator --keyring-backend test --chain-id $CHAIN_ID -y -b block \ +osmosisd tx wasm submit-proposal wasm-store $CONTRACT.wasm \ + --title "Add $CONTRACT" --summary "Let's upload this contract" \ + --authority osmo10d07y265gmmuvt4z0w9aw880jnsr700jjeq4qp \ + --from validator --keyring-backend test --chain-id $CHAIN_ID -y -b sync \ --gas 9000000 --gas-prices 0.05uosmo ``` @@ -77,13 +79,13 @@ osmosisd query gov proposal $PROPOSAL ## Deposit on proposal ``` osmosisd tx gov deposit $PROPOSAL 10000000uosmo --from validator --keyring-backend test \ - --chain-id $CHAIN_ID -y -b block --gas 6000000 --gas-prices 0.05uosmo + --chain-id $CHAIN_ID -y -b sync --gas 6000000 --gas-prices 0.05uosmo ``` ## Vote ``` osmosisd tx gov vote $PROPOSAL yes --from validator --keyring-backend test \ - --chain-id $CHAIN_ID -y -b block --gas 600000 --gas-prices 0.05uosmo + --chain-id $CHAIN_ID -y -b sync --gas 600000 --gas-prices 0.05uosmo ``` ## Check the results diff --git a/docs/build/developer-environment/cli.md b/docs/build/developer-environment/cli.md index 59695dc7f..6087b3d79 100644 --- a/docs/build/developer-environment/cli.md +++ b/docs/build/developer-environment/cli.md @@ -102,7 +102,7 @@ MYACCOUNT=$(osmosisd keys show testaccount -a --keyring-backend test) ``` The command above creates a local key-pair that is not yet registered on the chain. An account is created the first time it receives tokens from another account. - You can now send some tokens to this enw account. If you are connected to the testnet, you can get tokens from [https://faucet.osmosis.zone](https://faucet.osmosis.zone) + You can now send some tokens to this new account. If you are connected to the testnet, you can get tokens from [https://faucet.osmosis.zone](https://faucet.osmosis.zone) ```bash # Check that the testaccount account did receive the tokens. diff --git a/docs/build/developer-environment/ide-guide.md b/docs/build/developer-environment/ide-guide.md index 2f4592d15..e32d30d15 100644 --- a/docs/build/developer-environment/ide-guide.md +++ b/docs/build/developer-environment/ide-guide.md @@ -42,7 +42,7 @@ These are the VSCode extensions that are in daily use by the teams working on Os ## Vscode configuration -To make your environment run tests automatically every time you save" +To make your environment run tests automatically every time you save: Go to: `VSCode -> Preferences -> settings -> Extensions -> Go` diff --git a/docs/build/developer-environment/index.mdx b/docs/build/developer-environment/index.mdx index d152d07e4..91c90af47 100644 --- a/docs/build/developer-environment/index.mdx +++ b/docs/build/developer-environment/index.mdx @@ -10,7 +10,7 @@ import DocCardList from '@theme/DocCardList'; Set up the local toolchain you need before building on or against Osmosis. These pages are shared groundwork for chain development, CosmWasm work, and running a node. -**Install osmosisd** covers the binary's minimum specs and installation, and **Interact with the CLI** shows how to query and submit transactions with it. **Build and Test** compiles Osmosis from source, **IDE Setup** configures a Go development environment, and **Local Testing** spins up a containerized LocalOsmosis chain to develop against. **Key Management** covers creating, importing, and using keys, including multisig. +**Install osmosisd** covers the binary's minimum specs, installation, and building from source, and **Interact with the CLI** shows how to query and submit transactions with it. **IDE Setup** configures a Go development environment, and **Local Testing** spins up a containerized LocalOsmosis chain to develop against. **Key Management** covers creating, importing, and using keys, including multisig. The same `osmosisd` binary serves both developers and node operators, so node operators in the Validate section are pointed here for installation rather than duplicating it. diff --git a/docs/build/developer-environment/keys/keys-cli.md b/docs/build/developer-environment/keys/keys-cli.md index 71df1d4f7..c89991a9c 100644 --- a/docs/build/developer-environment/keys/keys-cli.md +++ b/docs/build/developer-environment/keys/keys-cli.md @@ -123,8 +123,8 @@ $ osmosisd keys show Default --bech acc $ osmosisd keys show Default --bech val - name: Default type: local - address: osmocncl1zdlttjrqh9jsgk2l8tgn6f0kxlfy98s3prz35z - pubkey: osmocnclpub1addwnpepq0ua07k8p3vrv5dap4pl77n4gjyyqsqrndzu0tdrr60ddhfg6ah0ck5ad5l + address: osmovaloper1zdlttjrqh9jsgk2l8tgn6f0kxlfy98s3prz35z + pubkey: osmovaloperpub1addwnpepq0ua07k8p3vrv5dap4pl77n4gjyyqsqrndzu0tdrr60ddhfg6ah0ck5ad5l mnemonic: "" threshold: 0 pubkeys: [] @@ -139,8 +139,8 @@ $ osmosisd keys show Default --bech val $ osmosisd keys show Default --bech cons - name: Default type: local - address: osmocnclcons1zdlttjrqh9jsgk2l8tgn6f0kxlfy98s34pfmlc - pubkey: osmocnclconspub1addwnpepq0ua07k8p3vrv5dap4pl77n4gjyyqsqrndzu0tdrr60ddhfg6ah0ch6kdrc + address: osmovalcons1zdlttjrqh9jsgk2l8tgn6f0kxlfy98s34pfmlc + pubkey: osmovalconspub1addwnpepq0ua07k8p3vrv5dap4pl77n4gjyyqsqrndzu0tdrr60ddhfg6ah0ch6kdrc mnemonic: "" threshold: 0 pubkeys: [] diff --git a/docs/build/developer-environment/keys/multisig.md b/docs/build/developer-environment/keys/multisig.md index 9ab3115cd..3be894699 100644 --- a/docs/build/developer-environment/keys/multisig.md +++ b/docs/build/developer-environment/keys/multisig.md @@ -75,16 +75,16 @@ osmosisd tx bank send \ --chain-id=osmosis-1 \ --gas=auto \ --fees=1000000uosmo \ - --broadcast-mode=block + --broadcast-mode=sync ``` ### Step 2: Create the multisig transaction -We want to send 5 OSMO from our multisig account to `osmo1rgjxswhuxhcrhmyxlval0qa70vxwvqn2e0srft`. +We want to send 5 OSMO from our multisig account `osmo1e0fx0q9meawrcq7fmma9x60gk35lpr4xk3884m` to `osmo157g6rn6t6k5rl0dl57zha2wx72t633axqyvvwq`. ```bash osmosisd tx bank send \ - osmo1rgjxswhuxhcrhmyxlval0qa70vxwvqn2e0srft \ + osmo1e0fx0q9meawrcq7fmma9x60gk35lpr4xk3884m \ osmo157g6rn6t6k5rl0dl57zha2wx72t633axqyvvwq \ 5000000uosmo \ --gas=200000 \ @@ -101,12 +101,12 @@ The file `unsignedTx.json` contains the unsigned transaction encoded in JSON. "messages": [ { "@type": "/cosmos.bank.v1beta1.MsgSend", - "from_address": "osmo1rgjxswhuxhcrhmyxlval0qa70vxwvqn2e0srft", + "from_address": "osmo1e0fx0q9meawrcq7fmma9x60gk35lpr4xk3884m", "to_address": "osmo157g6rn6t6k5rl0dl57zha2wx72t633axqyvvwq", "amount": [ { "denom": "uosmo", - "amount": "5000000000000000000" + "amount": "5000000" } ] } @@ -177,12 +177,12 @@ The TX is now signed: "messages": [ { "@type": "/cosmos.bank.v1beta1.MsgSend", - "from_address": "osmo1rgjxswhuxhcrhmyxlval0qa70vxwvqn2e0srft", + "from_address": "osmo1e0fx0q9meawrcq7fmma9x60gk35lpr4xk3884m", "to_address": "osmo157g6rn6t6k5rl0dl57zha2wx72t633axqyvvwq", "amount": [ { "denom": "uosmo", - "amount": "5000000000000000000" + "amount": "5000000" } ] } @@ -259,5 +259,5 @@ The TX is now signed: ```sh osmosisd tx broadcast signedTx.json \ --chain-id=osmosis-1 \ - --broadcast-mode=block + --broadcast-mode=sync ``` diff --git a/docs/build/developer-environment/osmosisd.md b/docs/build/developer-environment/osmosisd.md index d00092365..e89d02531 100644 --- a/docs/build/developer-environment/osmosisd.md +++ b/docs/build/developer-environment/osmosisd.md @@ -68,7 +68,7 @@ After installed, open new terminal to properly load go ## Install Osmosis Binary -Clone the osmosis repo and check out the current mainnet release tag (replace `v31.0.0` below with the latest tag from the [Osmosis releases](https://github.com/osmosis-labs/osmosis/releases) page): +Clone the osmosis repo and check out the current mainnet release tag (replace `v31.0.3` below with the latest tag from the [Osmosis releases](https://github.com/osmosis-labs/osmosis/releases) page): ```bash diff --git a/docs/build/frontend/build-a-dapp.md b/docs/build/frontend/build-a-dapp.md new file mode 100644 index 000000000..d8565306f --- /dev/null +++ b/docs/build/frontend/build-a-dapp.md @@ -0,0 +1,51 @@ +--- +title: Build a Dapp +description: Scaffold a frontend, connect a wallet, query Osmosis, and submit a swap. +sidebar_position: 1 +--- + +# Build a Dapp + +An end-to-end path for building a web app on Osmosis, tying the individual SDK pages into one walkthrough. Each tool has its own page with the full reference; this is the ordered happy path from scaffold to a working swap. + +## 1. Scaffold + +The quickest start is [create-cosmos-app](https://github.com/hyperweb-io/create-cosmos-app), which scaffolds a Cosmos dapp with wallet connection, signing, and proto support preconfigured: + +```bash +npx create-cosmos-app +``` + +It wires up [CosmosKit](/build/frontend/cosmos-kit) and [OsmoJS](/build/frontend/osmojs) for you. You can also add them to an existing app: + +```bash +npm install osmojs @cosmos-kit/react +``` + +## 2. Connect a wallet + +[CosmosKit](/build/frontend/cosmos-kit) is the React wallet adapter for the Cosmos ecosystem (Keplr, Leap, mobile via WalletConnect). Wrap your app in its provider and use its hooks to connect and read the active account. See the [CosmosKit page](/build/frontend/cosmos-kit) for the provider setup and the `useChain` hook that gives you the connected address and a signing client. + +## 3. Query chain data + +For reading prices, pools, and routing quotes, use the [Sidecar Query Server (SQS)](/integrate/endpoints/sqs), the same service the production frontend uses, over plain HTTP. For querying module state directly, [OsmoJS](/build/frontend/osmojs) ships typed query clients generated from the chain protos. + +## 4. Compose and broadcast a transaction + +[OsmoJS](/build/frontend/osmojs) composes and broadcasts Osmosis and Cosmos messages with proto and amino encoding handled for you: + +```ts +import { getSigningOsmosisClient } from 'osmojs'; + +const client = await getSigningOsmosisClient({ rpcEndpoint, signer }); +``` + +From there, building a swap follows the standard flow: get a quote from SQS, compose `MsgSwapExactAmountIn` from the route with a slippage-guarded minimum output, and broadcast it with the signing client. See the [Integrate](/integrate) section for the canonical swap flow, the message shape, and the hazards (exact-in vs exact-out, denom and exponent handling, the mandatory minimum-output guard). + +## Reference + +- [OsmoJS](/build/frontend/osmojs): message composition, signing, broadcasting. +- [Telescope](/build/frontend/telescope): the codegen tool behind OsmoJS, if you need custom bindings. +- [CosmosKit](/build/frontend/cosmos-kit): wallet connection and account management. +- [Osmosis Frontend](/build/frontend/osmosis-frontend): the architecture of app.osmosis.zone itself. +- [Integrate](/integrate): the quote-to-broadcast swap flow and other integration paths. diff --git a/docs/build/frontend/cosmos-kit.mdx b/docs/build/frontend/cosmos-kit.mdx index c6ab27629..fae957835 100644 --- a/docs/build/frontend/cosmos-kit.mdx +++ b/docs/build/frontend/cosmos-kit.mdx @@ -14,13 +14,13 @@ To get started with CosmosKit, follow the [How to use CosmosKit](https://docs.hy Here are some examples of CosmosKit hooks in action: -- [Dashboard](https://github.com/cosmology-tech/cosmos-kit/blob/main/packages/example/pages/index.tsx) -- [Name Service](https://github.com/cosmology-tech/cosmos-kit/blob/main/packages/example/pages/ns2.tsx) -- [Add Chain](https://github.com/cosmology-tech/cosmos-kit/blob/main/packages/example/pages/add-chain.tsx) -- [Global Wallet Status](https://github.com/cosmology-tech/cosmos-kit/blob/main/packages/example/pages/index.tsx) -- [Fetch Address](https://github.com/cosmology-tech/cosmos-kit/blob/main/packages/example/pages/index.tsx) -- [Fetch Balance & Send Tokens](https://github.com/cosmology-tech/cosmos-kit/blob/main/packages/example/pages/tx.tsx) -- [Vote](https://github.com/cosmology-tech/cosmos-kit/blob/main/packages/example/pages/gov.tsx) +- [Dashboard](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/example/pages/index.tsx) +- [Name Service](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/example/pages/ns2.tsx) +- [Add Chain](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/example/pages/add-chain.tsx) +- [Global Wallet Status](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/example/pages/index.tsx) +- [Fetch Address](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/example/pages/index.tsx) +- [Fetch Balance & Send Tokens](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/example/pages/tx.tsx) +- [Vote](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/example/pages/gov.tsx) ## Hooks @@ -37,9 +37,9 @@ CosmosKit provides several hooks to help you interact with the Cosmos ecosystem: CosmosKit consists of several packages: -- [@cosmos-kit/core](https://github.com/cosmology-tech/cosmos-kit/blob/main/packages/core/LICENSE): Core package of CosmosKit, including types, utils, and base classes. +- [@cosmos-kit/core](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/core/LICENSE): Core package of CosmosKit, including types, utils, and base classes. - [@cosmos-kit/react](https://www.npmjs.com/package/@cosmos-kit/react): A wallet adapter for React with mobile WalletConnect support for the Cosmos ecosystem. -- [@cosmos-kit/example](https://github.com/cosmology-tech/cosmos-kit/blob/main/packages/example): An example Next.js project integrating `@cosmos-kit/react` wallet adapter. +- [@cosmos-kit/example](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/example): An example Next.js project integrating `@cosmos-kit/react` wallet adapter. ## Wallet Developers diff --git a/docs/build/frontend/index.mdx b/docs/build/frontend/index.mdx index d23c496c5..22ee00ca8 100644 --- a/docs/build/frontend/index.mdx +++ b/docs/build/frontend/index.mdx @@ -9,7 +9,7 @@ import DocCardList from '@theme/DocCardList'; The tools for building applications and user interfaces on top of Osmosis in TypeScript and JavaScript. -**OsmoJS** is the SDK for composing and broadcasting Osmosis and Cosmos messages, with full transaction encoding. It is generated from the chain's protobuf definitions by **Telescope**, the codegen tool that produces TypeScript bindings from Cosmos SDK protos. **CosmosKit** handles wallet connection and account management across Cosmos wallets. The **Osmosis Frontend** page documents the architecture of app.osmosis.zone itself. +**Build a Dapp** is the end-to-end walkthrough that ties these together into a working application. **OsmoJS** is the SDK for composing and broadcasting Osmosis and Cosmos messages, with full transaction encoding. It is generated from the chain's protobuf definitions by **Telescope**, the codegen tool that produces TypeScript bindings from Cosmos SDK protos. **CosmosKit** handles wallet connection and account management across Cosmos wallets. The **Osmosis Frontend** page documents the architecture of app.osmosis.zone itself. These are client-side libraries for consuming Osmosis. For querying the chain's data and routing surfaces (SQS, RPC, REST), see Integrate; for smart contracts, see CosmWasm. diff --git a/docs/build/frontend/osmojs/README.md b/docs/build/frontend/osmojs/README.md index 5bc6bccf4..c9139b0f5 100644 --- a/docs/build/frontend/osmojs/README.md +++ b/docs/build/frontend/osmojs/README.md @@ -57,8 +57,6 @@ const msg = swapExactAmountIn({ }); ``` -(If you want to see an example of calculating `routes` and `tokenOutMinAmount` cosmology uses osmojs and has an [example here](https://github.com/cosmology-tech/cosmology/tree/main/packages/core#lookuproutesfortrade).) - ### Calculating Fees Make sure to create a `fee` object in addition to your message. @@ -309,7 +307,7 @@ const { ### Further examples -Examples in [`create-cosmos-app` repo's examples directory](https://github.com/cosmology-tech/create-cosmos-app/tree/main/examples) gives you a great guideline on how osmojs can be used at its full extent. +Examples in [`create-cosmos-app` repo's examples directory](https://github.com/hyperweb-io/create-cosmos-app/tree/main/examples) gives you a great guideline on how osmojs can be used at its full extent. You can also refer to the [osmojs documentation](https://github.com/osmosis-labs/osmojs/tree/main/packages/osmojs/docs) for further documentations on osmojs usage. diff --git a/docs/build/frontend/osmosis-frontend.mdx b/docs/build/frontend/osmosis-frontend.mdx index 301358992..7311407cd 100644 --- a/docs/build/frontend/osmosis-frontend.mdx +++ b/docs/build/frontend/osmosis-frontend.mdx @@ -55,7 +55,7 @@ npx turbo link ...press y (yes) and choose "OsmoLabs" as the Vercel build scope... ``` -2. Run local server at [`localhost:3000`](localhost:3000) +2. Run local server at [`localhost:3000`](http://localhost:3000) ```bash yarn dev diff --git a/docs/build/frontend/telescope/README.md b/docs/build/frontend/telescope/README.md index c85f4690e..90ac28c24 100644 --- a/docs/build/frontend/telescope/README.md +++ b/docs/build/frontend/telescope/README.md @@ -423,12 +423,12 @@ To broadcast messages, you'll want to use either [keplr](https://docs.keplr.app/ Likely you'll want to use the Amino, so unless you need proto, you should use this one: ```js -import { getOfflineSigner as getOfflineSignerAmino } from 'cosmjs-utils'; +import { getOfflineSigner as getOfflineSignerAmino } from 'osmojs'; ``` ### Proto Signer ```js -import { getOfflineSigner as getOfflineSignerProto } from 'cosmjs-utils'; +import { getOfflineSigner as getOfflineSignerProto } from 'osmojs'; ``` WARNING: NOT RECOMMENDED TO USE PLAIN-TEXT MNEMONICS. Please take care of your security and use best practices such as AES encryption and/or methods from 12factor applications. @@ -450,7 +450,7 @@ const mnemonic = Now that you have your `client`, you can broadcast messages: ```js -import { signAndBroadcast } from '@osmosnauts/helpers'; +import { signAndBroadcast } from 'osmojs'; const res = await signAndBroadcast({ client, // SigningStargateClient diff --git a/docs/build/index.mdx b/docs/build/index.mdx index 707ce47fe..7e18c8b30 100644 --- a/docs/build/index.mdx +++ b/docs/build/index.mdx @@ -7,11 +7,12 @@ import DocCardList from '@theme/DocCardList'; # Build on Osmosis -This section is for developers building on or extending Osmosis. It splits three ways by what you are building: +This section is for developers building on or extending Osmosis. It splits four ways by what you are building: -- **Chain Development** : the Osmosis chain itself. Set up a dev environment, build from source, run a local testnet, and read the specifications for every `x/` module (GAMM, concentrated liquidity, pool manager, gov, mint, superfluid, TWAP, and more). -- **CosmWasm** : smart contracts on Osmosis. Scaffolding with Beaker, deployment and verification, local and testnet workflows, and interacting with contracts from JavaScript. -- **Frontend** : the TypeScript and JavaScript SDKs for composing and broadcasting Osmosis transactions, including OsmoJS, Telescope, and CosmosKit. +- **Developer Environment** : the toolchain. Install `osmosisd`, build from source, manage keys, and spin up a local testnet to develop against. Start here. +- **Chain Development** : the Osmosis chain itself. Read the specifications for every `x/` module (GAMM, concentrated liquidity, pool manager, gov, mint, superfluid, TWAP, and more). +- **CosmWasm** : smart contracts on Osmosis. Scaffolding with cw-orchestrator, deployment and verification, local and testnet workflows, and interacting with contracts from JavaScript. +- **Frontend & SDKs** : the TypeScript and JavaScript SDKs for composing and broadcasting Osmosis transactions, including OsmoJS, Telescope, and CosmosKit. Pick the path that matches what you are building. If you are integrating an existing application against Osmosis rather than extending the protocol, see Integrate instead. diff --git a/docs/integrate/endpoints/grpc.md b/docs/integrate/endpoints/grpc.md index aeccba3dc..566f8db2c 100644 --- a/docs/integrate/endpoints/grpc.md +++ b/docs/integrate/endpoints/grpc.md @@ -18,7 +18,7 @@ If you are running your own node. It's also possible to enable them by editing ## Grpc endpoints An overview of all available gRPC endpoints shipped with Osmosis is available in the [Osmosis Protobuf documentation](https://buf.build/osmosis-labs/osmosis). There is also a Cosmos SDK is [Protobuf documentation](https://buf.build/cosmos/cosmos-sdk). -You can send requests to the gRPC server using a gRPC client such as [grpcurl](#grpcurl) or from [Buf Studio](#buf-studio). +You can send requests to the gRPC server using a gRPC client such as [grpcurl](#grpcurl) or by browsing the [Buf Schema Registry](#buf-schema-registry). Since the code generation library largely depends on your own tech stack, we will only present three alternatives: diff --git a/docs/learn/get-started.md b/docs/learn/get-started.md index 584549f30..7e9d4fff1 100644 --- a/docs/learn/get-started.md +++ b/docs/learn/get-started.md @@ -4,10 +4,6 @@ sidebar_position: 3 --- # Getting Started - - This page gets you set up: install a wallet, connect to the app, and deposit funds onto Osmosis over IBC. Once you have funds, see [How Trading Works](/learn/how-trading-works) to make your first swap and [Providing Liquidity](/learn/providing-liquidity) to start earning. ## Set up a Wallet diff --git a/docusaurus.config.js b/docusaurus.config.js index 08043e43a..039e1b185 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -31,7 +31,7 @@ const mathRemark = [remarkMath, { singleDollarTextMath: false }]; // Single docs instance rooted at `docs/`, served at the site root so existing // URLs are preserved (docs/osmosis-core/... -> /osmosis-core/...). One sidebar // follows the reader across all sections (the fix for the former per-section -// isolated sidebars). MTN-88 Phase 1: collapse only; the folder->taxonomy +// isolated sidebars). This is the collapse-only step; the folder->taxonomy // reorganization and redirects come in a later phase. const docsPlugin = [ '@docusaurus/plugin-content-docs', @@ -48,7 +48,7 @@ const docsPlugin = [ }), ]; -// In-repo backstop for the URL changes from the IA restructure (MTN-88). +// In-repo backstop for the URL changes from the IA restructure. // Vercel serves the canonical 301s (vercel.json `redirects`), but this client // redirect keeps old paths resolving on local/preview builds where Vercel rules // do not apply. The full old->new map is generated from the page move plan. @@ -150,6 +150,7 @@ const config = { label: 'Build', position: 'left', items: [ + { label: 'Developer Environment', to: 'build/developer-environment' }, { label: 'Chain Development', to: 'build/chain' }, { label: 'CosmWasm', to: 'build/cosmwasm' }, { label: 'Frontend & SDKs', to: 'build/frontend' }, @@ -265,7 +266,7 @@ const config = { appId: 'F26GLV8TNU', apiKey: '0c5c06782dec165349c88655f2de36b6', indexName: 'Docs', - // Kept off through the MTN-88 single-instance migration: the new index + // Kept off through the single-instance migration: the new index // has faceting configured, but page `docusaurus_tag` values will flip // from per-section to `docs-default-current` on that merge and lag the // index by one crawl. Re-enable once the structure has settled. diff --git a/src/css/custom.css b/src/css/custom.css index be5dcd486..029c61e29 100644 --- a/src/css/custom.css +++ b/src/css/custom.css @@ -938,7 +938,7 @@ img[src$='#terminal'] { } /* Force the mobile-style hamburger navbar earlier than Docusaurus's - default 996px breakpoint. After the IA restructure (MTN-88) the navbar + default 996px breakpoint. After the IA restructure the navbar has only 5 short left items (Learn, Integrate, Build, Validate, Community) plus the right-side icons, search, and Launch Dex, so it fits much further down than the old 8-item bar did. The early-hamburger