diff --git a/.gitbook/README.mdx b/.gitbook/README.mdx deleted file mode 100644 index 3b837f7..0000000 --- a/.gitbook/README.mdx +++ /dev/null @@ -1,51 +0,0 @@ ---- -description: >- - Injective is a high-performance, interoperable layer-one blockchain for - building premier Web3 financial applications. ---- - -# About Injective - -## What is Injective? - -Injective is the blockchain built for finance. - -It is the only blockchain where developers can use pre-built, customizable [modules](developers-native/README.md) to create dynamic applications that aren't possible on other networks. Combined with optimizations to its core architecture and enhanced cross-chain interoperability, Injective offers a high-performance network, ready to efficiently and securely bring the global financial system on-chain. - ----- - - - - -{/* */} - - - - - - -
Getting StartedStart your Injective Journeygetting-startedstart-hero.png
Are you a User?Learn how to create a walletwalletuser-hero.png
Do you want to use DeFi?Learn how to start trading on Injectivedefitrader-hero.png
Do you want to run infrastructure?Learn how to run sentry and validator nodesinfravalidator-hero.png
Are you a developer?Learn how to build on Injectivedevelopersdev-hero.png
Need Help?Join the Injective Discord
Join the Developer Telegram
#developer-supportexplorer-hero.png
- -# Getting Started - -Welcome to your journey of exploring Injective! Before asking questions, please try using the search functionality in the docs. Our goal is to make the documentation self-sufficient, ensuring that onboarding is smooth and everyone can easily learn more about Injective. - -## Quickstart Guide to Injective - - - - - - - - - - -
WalletLearn how to create a wallet on Injective and see the supported wallets on Injective wallet-hero-2.pngwallet
Token StandardsLearn about different Token Standards on Injectivetoken-hero.pngtoken-standards
TransactionsLearn how to prepare, sign and submit transactions on Injectivetxs-hero.pngtransactions
- -## Need Help? - -Should you have some questions or feedback, you can reach out to Discord or Telegram: - -* Join the [Injective Discord server](https://discord.gg/injective) and find the relevant channel. -* Join the [Injective Developer Telegram channel](https://t.me/+8Y_0HOFLhnRlZDU9). diff --git a/.gitbook/SUMMARY.md b/.gitbook/SUMMARY.md.bak similarity index 100% rename from .gitbook/SUMMARY.md rename to .gitbook/SUMMARY.md.bak diff --git a/.gitbook/defi.mdx b/.gitbook/defi.mdx deleted file mode 100644 index 35a9026..0000000 --- a/.gitbook/defi.mdx +++ /dev/null @@ -1,9 +0,0 @@ ---- -description: >- - This section helps traders to learn more about trading instruments and start - trading on Injective ---- - -# DeFi - -Here you can find a comprehensive overview of the Injective's **exchange module**, as well as tutorials, guides, reward programs, leaderboard competitions, and general resources for developers and API traders. diff --git a/.gitbook/defi/bridge.mdx b/.gitbook/defi/bridge.mdx index 217ec3f..4b6470c 100644 --- a/.gitbook/defi/bridge.mdx +++ b/.gitbook/defi/bridge.mdx @@ -1,3 +1,5 @@ -# Bridge +--- +title: Bridge +--- Bridging assets into the Injective ecosystem is effortless, with support for 23+ networks and growing. Here, you'll find step-by-step instructional guides for bridging assets from Ethereum, Solana, via IBC, and using the Wormhole protocol, making it easy to connect with Injective's ecosystem. diff --git a/.gitbook/defi/community-burn.mdx b/.gitbook/defi/community-burn.mdx index a0e86be..393f858 100644 --- a/.gitbook/defi/community-burn.mdx +++ b/.gitbook/defi/community-burn.mdx @@ -1,4 +1,6 @@ -# Community Burn +--- +title: Community Burn +--- ### What is the Community Burn? diff --git a/.gitbook/defi/governance.mdx b/.gitbook/defi/governance.mdx index e0ca274..1943f25 100644 --- a/.gitbook/defi/governance.mdx +++ b/.gitbook/defi/governance.mdx @@ -1,4 +1,6 @@ -# Governance +--- +title: Governance +--- ## Governance @@ -29,4 +31,3 @@ If a proposal passes, Injective contributors will begin to work together to put * For more details on the governance proposal process, read Injective's [blog](https://injective.com/blog/injective-governance-proposal-procedure/). * To participate in blockchain governance, join the [Injective Discord](https://discord.com/invite/NK4qdbv) or the [Injective Governance Forum](https://gov.injective.network). * Visit the [Injective Hub](https://injhub.com/governance) to view Injective proposals and participate in voting. - diff --git a/.gitbook/defi/index.mdx b/.gitbook/defi/index.mdx new file mode 100644 index 0000000..1c4b868 --- /dev/null +++ b/.gitbook/defi/index.mdx @@ -0,0 +1,8 @@ +--- +title: DeFi +description: >- + This section helps traders to learn more about trading instruments and start + trading on Injective +--- + +Here you can find a comprehensive overview of Injective's **exchange module**, as well as tutorials, guides, reward programs, leaderboard competitions, and general resources for developers and API traders. diff --git a/.gitbook/defi/open-liquidity-program/eligibility.mdx b/.gitbook/defi/open-liquidity-program/eligibility.mdx index 90fe3f3..5bc77e1 100644 --- a/.gitbook/defi/open-liquidity-program/eligibility.mdx +++ b/.gitbook/defi/open-liquidity-program/eligibility.mdx @@ -1,16 +1,15 @@ --- description: How to Qualify and Remain Qualified for OLP Rewards +title: Eligibility --- -# Eligibility - ## Clean Slate Qualification An Injective address can qualify for OLP by meeting the following criteria: * The **address must be opted out of the Trade & Earn (T\&E) program** prior to the start of the qualification process. The address will not earn T\&E rewards during the qualification process. See examples in [Python](https://github.com/InjectiveLabs/sdk-python/blob/master/examples/chain\_client/24\_MsgRewardsOptOut.py), [Go](https://github.com/InjectiveLabs/sdk-go/blob/master/examples/chain/24\_MsgRegisterAsDMM/example.go), and [TS](https://github.com/InjectiveLabs/injective-ts/wiki/04CoreModulesExchange#msgrewardsoptout) for opting out programatically. * Note: Eligibility for the qualification process begins at 00:00 UTC the day after the opt out is complete. To check if an address has been successfully opted out of T\&E, [this list can be cross referenced](https://lcd.injective.network/injective/exchange/v1beta1/opted\_out\_of\_rewards\_accounts). -* The address's maker volume must account for **at least 0.25% of the total daily exchange maker volume of** [**eligible markets**](./eligible-markets.md) **for 3 days in a row** in the same epoch. Self trading is strictly prohibited. +* The address's maker volume must account for **at least 0.25% of the total daily exchange maker volume of** [**eligible markets**](./eligible-markets/) **for 3 days in a row** in the same epoch. Self trading is strictly prohibited. Assuming both of these requirements have been met, the address will qualify for OLP rewards on the 4th day at 00:00 UTC. Once qualified, an address will remain eligible for rewards through the rest of the epoch unless special circumstances (e.g. abusing the system, wash trading, etc.) compel the removal of the address. Note that activity prior to qualification will not count towards rewards. @@ -22,17 +21,17 @@ See [documentation on the Injective `authz` module](https://docs.injective.netwo ## Maintaining Next Epoch Eligibility/Pre-Qualification -To automatically qualify for the next epoch after qualifying for the current epoch, an **address must account for at least 0.25% of total exchange maker volume** of [eligible markets](./eligible-markets.md) (not including KAVA reward markets) from the date of qualification to the last day of the epoch. +To automatically qualify for the next epoch after qualifying for the current epoch, an **address must account for at least 0.25% of total exchange maker volume** of [eligible markets](./eligible-markets/) (not including KAVA reward markets) from the date of qualification to the last day of the epoch. -* Example: Address `inj1a` enters epoch 21 ineligible for OLP rewards. `inj1a` accounts for 1%, 0.1%, and 0.2% of total daily exchange maker volume of [eligible markets](./eligible-markets.md) on days 1, 2, and 3 of epoch 21, respectively. On days 4, 5, and 6, `inj1a` accounts for 0.5% of the applicable volume each day. `inj1a` qualifies on day 7 of the epoch. To maintain eligibility/qualification for epoch 22, `inj1a` must account for at least 0.25% of the cumulative applicable maker volume from day 7 through day 28 of epoch 21. If the cumulative maker volume of [eligible markets](./eligible-markets.md) for this period (days 7 through 28) was $100M, then `inj1a` must account for $250,000 of cumulative maker volume in those markets within the same period. +* Example: Address `inj1a` enters epoch 21 ineligible for OLP rewards. `inj1a` accounts for 1%, 0.1%, and 0.2% of total daily exchange maker volume of [eligible markets](./eligible-markets/) on days 1, 2, and 3 of epoch 21, respectively. On days 4, 5, and 6, `inj1a` accounts for 0.5% of the applicable volume each day. `inj1a` qualifies on day 7 of the epoch. To maintain eligibility/qualification for epoch 22, `inj1a` must account for at least 0.25% of the cumulative applicable maker volume from day 7 through day 28 of epoch 21. If the cumulative maker volume of [eligible markets](./eligible-markets/) for this period (days 7 through 28) was $100M, then `inj1a` must account for $250,000 of cumulative maker volume in those markets within the same period. -If the address was eligible for the entire epoch through a previous epoch's pre-qualification, that address must account for at least 0.25% of the maker volume of [eligible markets](./eligible-markets.md) in the entire epoch. +If the address was eligible for the entire epoch through a previous epoch's pre-qualification, that address must account for at least 0.25% of the maker volume of [eligible markets](./eligible-markets/) in the entire epoch. * Example: Address `inj1a` enters epoch 22 prequalified from maintaining eligibility in epoch 21. Suppose the cumulative maker volume of [eligible markets](./eligible-markets.md) in epoch 22 totals $200M. Then `inj1a` must contribute at least $500,000 of the $200M in [eligible markets](./eligible-markets.md) by the end of epoch 22 to maintain automatic eligibility for epoch 23. ## Disqualification -**Any address that fails to account for at least 0.25% of applicable maker volume in an epoch will be disqualified from OLP at the start of the next epoch**. If the address wishes to rejoin the program, the address must go through the [clean slate qualification process](eligibility.md#clean-slate-qualification) again (though the address does not have to opt out of T\&E another time). Note that any liquidity contributed on days that the address is not eligible will not be rewarded retroactively once the address requalifies. +**Any address that fails to account for at least 0.25% of applicable maker volume in an epoch will be disqualified from OLP at the start of the next epoch**. If the address wishes to rejoin the program, the address must go through the [clean slate qualification process](./eligibility/#clean-slate-qualification) again (though the address does not have to opt out of T\&E another time). Note that any liquidity contributed on days that the address is not eligible will not be rewarded retroactively once the address requalifies. Disqualification occurs at the end of each epoch, meaning addresses continue to accrue rewards within the epoch regardless of next epoch eligibility. diff --git a/.gitbook/defi/open-liquidity-program/eligible-markets.mdx b/.gitbook/defi/open-liquidity-program/eligible-markets.mdx index 838ef9d..0d7faa8 100644 --- a/.gitbook/defi/open-liquidity-program/eligible-markets.mdx +++ b/.gitbook/defi/open-liquidity-program/eligible-markets.mdx @@ -1,9 +1,8 @@ --- description: Markets Eligible for Rewards in OLP +title: Eligible Markets --- -# Eligible Markets - To view a list of markets currently eligible for OLP rewards, please refer to the [OLP Dashboard](https://trading.injective.network/program/liquidity): diff --git a/.gitbook/defi/open-liquidity-program/epochs.mdx b/.gitbook/defi/open-liquidity-program/epochs.mdx index a8b2a14..15292fa 100644 --- a/.gitbook/defi/open-liquidity-program/epochs.mdx +++ b/.gitbook/defi/open-liquidity-program/epochs.mdx @@ -1,14 +1,12 @@ --- description: OLP Epoch Duration and Schedule +title: Epochs --- -# Epochs - -An epoch is the period of time in which market makers are evaluated based on their relative performance. Several metrics are cumulatively tracked during each epoch, which reset upon the commencement of a new epoch. Rewards are disbursed after the completion each epoch (see [Rewards Disbursement](reward-disbursements.md)). Currently, **each epoch is 28 days long**. +An epoch is the period of time in which market makers are evaluated based on their relative performance. Several metrics are cumulatively tracked during each epoch, which reset upon the commencement of a new epoch. Rewards are disbursed after the completion each epoch (see [Rewards Disbursement](./reward-disbursements/)). Currently, **each epoch is 28 days long**. The **first public OLP epoch (epoch 21) began on June 13, 2023 at 0:00 UTC**. Start and end dates for OLP epochs can be found in the following table, which is updated occasionally (typically a few months in advance) to include future epochs :
EpochStart Date (UTC)End Date (UTC)
21Jun 13, 2023 00:00:00 Jul 11, 2023 00:00:00 
22Jul 11, 2023 00:00:00 Aug 8, 2023 00:00:00 
23Aug 8, 2023 00:00:00 Sep 5, 2023 00:00:00 
24Sep 5, 2023 00:00:00 Oct 3, 2023 00:00:00 
25Oct 3, 2023 00:00:00 Oct 31, 2023 00:00:00 
26Oct 31, 2023 00:00:00 Nov 28, 2023 00:00:00 
27Nov 28, 2023 00:00:00 Dec 26, 2023 00:00:00 
28Dec 26, 2023 00:00:00 Jan 23, 2024 00:00:00 
29Jan 23, 2024 00:00:00 Feb 20, 2024 00:00:00 
30Feb 20, 2024 00:00:00 Mar 19, 2024 00:00:00 
31Mar 19, 2024 00:00:00 Apr 16, 2024 00:00:00 
32Apr 16, 2024 00:00:00 May 14, 2024 00:00:00 
33May 14, 2024 00:00:00 Jun 11, 2024 00:00:00 
34Jun 11, 2024 00:00:00 July 9, 2024 00:00:00
35July 9, 2024 00:00:00Aug 6, 2024 00:00:00
36Aug 6, 2024 00:00:00Sep 3, 2024 00:00:00
37Sep 3, 2024 00:00:00Oct 1, 2024 00:00:00
38Oct 1, 2024 00:00:00Oct 29, 2024 00:00:00
39Oct 29, 2024 00:00:00Nov 26, 2024 00:00:00
40Nov 26, 2024 00:00:00Dec 24, 2024 00:00:00
41Dec 24, 2024 00:00:00Jan 21, 2025 00:00:00
42Jan 21, 2025 00:00:00Feb 18, 2025 00:00:00
43Feb 18, 2025 00:00:00Mar 18, 2025 00:00:00
44Mar 18, 2025 00:00:00Apr 15, 2025 00:00:00
45Apr 15, 2025 00:00:00May 13, 2025 00:00:00
46May 13, 2025 00:00:00Jun 10, 2025 00:00:00
47Jun 10, 2025 00:00:00July 8, 2025 00:00:00
48July 8, 2025 00:00:00Aug 5, 2025 00:00:00
49Aug 5, 2025 00:00:00Sep 2, 2025 00:00:00
50Sep 2, 2025 00:00:00Sep 30, 2025 00:00:00
51Sep 30, 2025 00:00:00Oct 28, 2025 00:00:00
52Oct 28, 2025 00:00:00Nov 25, 2025 00:00:00
53Nov 25, 2025 00:00:00Dec 23, 2025 00:00:00
- diff --git a/.gitbook/defi/open-liquidity-program/fee-tiers.mdx b/.gitbook/defi/open-liquidity-program/fee-tiers.mdx index f2898d2..864bd8d 100644 --- a/.gitbook/defi/open-liquidity-program/fee-tiers.mdx +++ b/.gitbook/defi/open-liquidity-program/fee-tiers.mdx @@ -1,6 +1,7 @@ -# Fee Tiers +--- +title: Fee Tiers +--- Traders who meet threshold criteria for minimum staked INJ and minimum trading volume on a 28-day rolling basis are eligible for discounts on Injective trading fees. More information can be found on the page linked below. - diff --git a/.gitbook/defi/open-liquidity-program/flexible-reward-allocations.mdx b/.gitbook/defi/open-liquidity-program/flexible-reward-allocations.mdx index f3b0d7b..aaec0ba 100644 --- a/.gitbook/defi/open-liquidity-program/flexible-reward-allocations.mdx +++ b/.gitbook/defi/open-liquidity-program/flexible-reward-allocations.mdx @@ -1,10 +1,9 @@ --- description: OLP Reward Allocations to Markets and Institutional Liquidity Providers +title: Flexible Reward Allocations --- -# Flexible Reward Allocations - -Part of the changes implemented for epoch 43 include a fully discretionary dynamic reward to bootstrap liquidity for certain markets at specific times. Following the exact same calculations detailed in [reward-allocations.md](reward-allocations.md "mention"), and the classic formula/scoring methodology to determine a liquidity provider's share of the total reward for a market, this will be accomplished through the concept of Mini Epochs. +Part of the changes implemented for epoch 43 include a fully discretionary dynamic reward to bootstrap liquidity for certain markets at specific times. Following the exact same calculations detailed in [reward-allocations.md](./reward-allocations/ "mention"), and the classic formula/scoring methodology to determine a liquidity provider's share of the total reward for a market, this will be accomplished through the concept of Mini Epochs. Mini Epochs are flexible in that they are not constrained by the typical 00:00 UTC starting/ending point for a pair to exist in a Primary Epoch. Mini Epochs can begin or end at any time within a Primary Epoch, though they cannot span across multiple epochs. diff --git a/.gitbook/defi/open-liquidity-program/formula-parameters.mdx b/.gitbook/defi/open-liquidity-program/formula-parameters.mdx index cc64dd0..feff6b2 100644 --- a/.gitbook/defi/open-liquidity-program/formula-parameters.mdx +++ b/.gitbook/defi/open-liquidity-program/formula-parameters.mdx @@ -1,9 +1,8 @@ --- description: Values for OLP Formula Parameters +title: Formula Parameters --- -# Formula Parameters -
ParameterDefinitionValue (Subject to Change)
aLiquidity Score exponent0.4
bUptime Score exponent3
cVolume exponent0.8
MinDepthMinimum notional order size needed to generate points for Total Score$1000 through epoch 48
$4000 from epoch 49
MaxSpreadMaximum allowable spread against mid-price in an order to generate points for Total Score50 bps for BTC and ETH perp markets, 100 bps for all other eligible markets
diff --git a/.gitbook/defi/open-liquidity-program.mdx b/.gitbook/defi/open-liquidity-program/index.mdx similarity index 64% rename from .gitbook/defi/open-liquidity-program.mdx rename to .gitbook/defi/open-liquidity-program/index.mdx index 591ef2f..b22139a 100644 --- a/.gitbook/defi/open-liquidity-program.mdx +++ b/.gitbook/defi/open-liquidity-program/index.mdx @@ -1,6 +1,4 @@ --- description: Rewards for liquidity providers on Injective +title: Open Liquidity Program (OLP) --- - -# Open Liquidity Program (OLP) - diff --git a/.gitbook/defi/open-liquidity-program/introduction.mdx b/.gitbook/defi/open-liquidity-program/introduction.mdx index 603bdda..5709f2c 100644 --- a/.gitbook/defi/open-liquidity-program/introduction.mdx +++ b/.gitbook/defi/open-liquidity-program/introduction.mdx @@ -1,9 +1,8 @@ --- description: An Introduction to the Open Liquidity Program (OLP) +title: Introduction --- -# Introduction - As the fastest blockchain dedicated to revolutionizing finance, Injective provides robust liquidity across its ecosystem. Injective uniquely provides the world's first truly on-chain orderbook environment to bring shared liquidity across all DeFi applications. By relentlessly pursuing deeper liquidity, Injective empowers users and protocols with seamless access to capital-efficient markets not available elsewhere. diff --git a/.gitbook/defi/open-liquidity-program/performance-tracking.mdx b/.gitbook/defi/open-liquidity-program/performance-tracking.mdx index 054dd9f..5a0f665 100644 --- a/.gitbook/defi/open-liquidity-program/performance-tracking.mdx +++ b/.gitbook/defi/open-liquidity-program/performance-tracking.mdx @@ -1,9 +1,8 @@ --- description: OLP Dashboard +title: Performance Tracking --- -# Performance Tracking - Current and historical information on market allocations, expected/earned rewards, scores per market, and eligibility can be found on the [OLP Dashboard](https://trading.injective.network/program/liquidity) in the [Injective Trading Portal](https://trading.injective.network/). Snapshot data can be found under the [Scores tab](https://trading.injective.network/program/liquidity/scores). CSV files can also be downloaded in the [Scores tab](https://trading.injective.network/program/liquidity/scores) to view scores for all addresses and all markets at the same time—this information may be helpful for market participants that wish to view data on a broad level. diff --git a/.gitbook/defi/open-liquidity-program/program-details.mdx b/.gitbook/defi/open-liquidity-program/program-details.mdx index bc3e691..93da993 100644 --- a/.gitbook/defi/open-liquidity-program/program-details.mdx +++ b/.gitbook/defi/open-liquidity-program/program-details.mdx @@ -1,9 +1,8 @@ --- description: OLP Program Overview +title: Program Details --- -# Program Details - To promote deep, lasting liquidity across the Injective on-chain orderbook, the following metrics are prioritized by OLP: * **Dual-sided liquidity** (both bid and ask liquidity) diff --git a/.gitbook/defi/open-liquidity-program/reward-allocations-legacy.mdx b/.gitbook/defi/open-liquidity-program/reward-allocations-legacy.mdx index bf0770e..aa9f200 100644 --- a/.gitbook/defi/open-liquidity-program/reward-allocations-legacy.mdx +++ b/.gitbook/defi/open-liquidity-program/reward-allocations-legacy.mdx @@ -1,12 +1,11 @@ --- description: OLP Reward Allocations (through Epoch 42) +title: Reward Allocations (Legacy) --- -# Reward Allocations (Legacy) - ## Market Reward Allocations -Rewards are allocated to [eligible markets](eligible-markets.md) in two different methods: +Rewards are allocated to [eligible markets](./eligible-markets/) in two different methods: 1. Static allocations 2. Static allocations with a dynamic component @@ -45,7 +44,7 @@ $$ $$Other\ Preallocations$$ refers to the static market reward allocations for non-BTC, ETH, and INJ perp markets. -For more information on $$TAR$$ each epoch, see the [Reward Pool](./rewards.md) page. +For more information on $$TAR$$ each epoch, see the [Reward Pool](./rewards/) page. For each eligible market, the product of the MM[^1]’s $$LS^{0.7}$$ and $$Volume$$ is aggregated across all MMs. Rewards are allocated to each market based on the proportional aggregate products across all applicable markets. The preallocation amount (1%) for the market is also added in. @@ -62,7 +61,7 @@ $$ Rewards_{max} = TAR\ *\ \frac{1 - 0.375}{n}*2 $$ -Any reward allocations that exceed the cap will be redistributed amongst the other eligible markets according to the [dynamic allocation formula](reward-allocations-legacy.md#dynamic-market-reward-allocations). +Any reward allocations that exceed the cap will be redistributed amongst the other eligible markets according to the [dynamic allocation formula](./reward-allocations-legacy/#dynamic-market-reward-allocations).
# Eligible Markets Excluding BTC/ETH/INJ PerpsRewards Cap
620.83% of Total Available Rewards
717.86% of Total Available Rewards
815.63% of Total Available Rewards
913.89% of Total Available Rewards
1012.50% of Total Available Rewards
1111.36% of Total Available Rewards
1210.42% of Total Available Rewards
......
@@ -74,7 +73,7 @@ $$ Rewards_{MM_i} = \sum_{Market}\left(Rewards_{Market} * \frac {TS_{MM_i, \ Market}} {\sum_{MM} TS_{MM,\ Market}} \right) $$ -**Each** [**MM**](#user-content-fn-3)[^3] **will receive rewards based on the** [**MM**](#user-content-fn-4)[^4]**’s proportional**[ $$TS$$ ](./scoring.md#total-score)**within the market, subject to governance approval.** +**Each** [**MM**](#user-content-fn-3)[^3] **will receive rewards based on the** [**MM**](#user-content-fn-4)[^4]**’s proportional**[ $$TS$$ ](./scoring/#total-score)**within the market, subject to governance approval.** Rewards for addresses totaling < 1 INJ at the end of each epoch will be disregarded to reduce the overhead of the disbursement process. diff --git a/.gitbook/defi/open-liquidity-program/reward-allocations.mdx b/.gitbook/defi/open-liquidity-program/reward-allocations.mdx index ac43245..9c8dacb 100644 --- a/.gitbook/defi/open-liquidity-program/reward-allocations.mdx +++ b/.gitbook/defi/open-liquidity-program/reward-allocations.mdx @@ -1,12 +1,11 @@ --- description: OLP Reward Allocations (Epoch 43 Onwards) +title: Reward Allocations --- -# Reward Allocations - ## Market Reward Allocations -Rewards are allocated to [eligible markets](eligible-markets.md) in three different methods : +Rewards are allocated to [eligible markets](./eligible-markets/) in three different methods : 1. Static allocations 2. Minimum allocation with a dynamic component @@ -76,7 +75,7 @@ $$ where _TPR_ is equal to the percentage (expressed as a decimal) of total preallocated rewards (currently 0.375) and _n_ is the number of non-preallocated pairs. -Any reward allocations that exceed the cap will be redistributed amongst the other eligible markets according to the [dynamic allocation formula](reward-allocations.md#dynamic-market-reward-allocations). +Any reward allocations that exceed the cap will be redistributed amongst the other eligible markets according to the [dynamic allocation formula](./reward-allocations/#dynamic-market-reward-allocations). ## Reward Allocations @@ -86,10 +85,10 @@ $$ Rewards_{MM_i} = \sum_{Market}\left(Rewards_{Market} * \frac {TS_{MM_i, \ Market}} {\sum_{MM} TS_{MM,\ Market}} \right) $$ -**Each institutional liquidity provider** **will receive rewards based on their proportional**[ $$TS$$ ](./scoring.md#total-score)**within the market, subject to governance approval.** +**Each institutional liquidity provider** **will receive rewards based on their proportional**[ $$TS$$ ](./scoring/#total-score)**within the market, subject to governance approval.** Rewards for addresses totaling < 1 INJ at the end of each epoch will be disregarded to reduce the overhead of the disbursement process. -For the reward allocation process up through epoch 42, please see [reward-allocations-legacy.md](reward-allocations-legacy.md "mention"). +For the reward allocation process up through epoch 42, please see [reward-allocations-legacy.md](./reward-allocations-legacy/ "mention"). diff --git a/.gitbook/defi/open-liquidity-program/reward-disbursements.mdx b/.gitbook/defi/open-liquidity-program/reward-disbursements.mdx index cf25ffc..b80fcf0 100644 --- a/.gitbook/defi/open-liquidity-program/reward-disbursements.mdx +++ b/.gitbook/defi/open-liquidity-program/reward-disbursements.mdx @@ -1,9 +1,8 @@ --- description: How OLP Rewards Are Disbursed +title: Reward Disbursements --- -# Reward Disbursements - OLP Rewards are sent directly to the participants' addresses after the end of each epoch. **Half of the earned INJ rewards are paid out immediately, while the other half is subject to a 3 epoch vesting period**. If the address is inactive (earns rewards < 1 INJ) for any epoch during the vesting period, the vested rewards will be subject to forfeiture. All rewards are subject to governance approval, and all addresses eligible for more than 500 INJ per epoch are subject to KYC/KYB verification before their reward disbursement is included in a governance proposal submitted by Injective Labs. While any address can permissionlessly join OLP, reward eligibility is dependent on KYC/KYB. diff --git a/.gitbook/defi/open-liquidity-program/rewards.mdx b/.gitbook/defi/open-liquidity-program/rewards.mdx index 179fa58..335dd4f 100644 --- a/.gitbook/defi/open-liquidity-program/rewards.mdx +++ b/.gitbook/defi/open-liquidity-program/rewards.mdx @@ -1,12 +1,11 @@ --- description: Earn Unmatched Rewards in OLP +title: Rewards --- -# Rewards - Rewards for OLP are disbursed in the form of INJ, Injective's native utility and governance token. -Currently, **40,000 INJ** can be earned by eligible participants during each epoch (28 day period). This amount may be reassessed in advance for future epochs, or retroactively reduced for a current epoch as a result of one or more volatility response modifications (VRMs). For more information on OLP epochs, see [Epochs](epochs.md). +Currently, **40,000 INJ** can be earned by eligible participants during each epoch (28 day period). This amount may be reassessed in advance for future epochs, or retroactively reduced for a current epoch as a result of one or more volatility response modifications (VRMs). For more information on OLP epochs, see [Epochs](./epochs/). All rewards are subject to governance approval by the Injective community. diff --git a/.gitbook/defi/open-liquidity-program/scoring.mdx b/.gitbook/defi/open-liquidity-program/scoring.mdx index 30ebdef..4489df4 100644 --- a/.gitbook/defi/open-liquidity-program/scoring.mdx +++ b/.gitbook/defi/open-liquidity-program/scoring.mdx @@ -1,9 +1,8 @@ --- description: Scoring a Market Maker's Epoch Performance in a Single Market +title: Scoring Formula/Methodology --- -# Scoring Formula/Methodology - ## Total Score For any given market, an MM's (Market Maker's) $$TS$$ (Total Score) in an epoch is calculated as: @@ -12,10 +11,10 @@ $$ TS_{Market} = (LS_{Epoch})^a \cdot (Uptime_{Epoch})^b \cdot (Volume_{epoch})^c $$ -where $$LS_{epoch}$$ is the MM's [Liquidity Score](./scoring.md#liquidity-score) in the market in the epoch, $$Uptime_{Epoch}$$is the MM's [Uptime score](./scoring.md#uptime-score) in the market in the epoch, and $$Volume_{epoch}$$ is the MM's total volume (maker and taker) in the market in the epoch. +where $$LS_{epoch}$$ is the MM's [Liquidity Score](./scoring/#liquidity-score) in the market in the epoch, $$Uptime_{Epoch}$$is the MM's [Uptime score](./scoring/#uptime-score) in the market in the epoch, and $$Volume_{epoch}$$ is the MM's total volume (maker and taker) in the market in the epoch. -$$a$$, $$b$$, and $$c$$ are exponent [parameters](formula-parameters.md) that weight the different components of the formula. +$$a$$, $$b$$, and $$c$$ are exponent [parameters](./formula-parameters/) that weight the different components of the formula. ## Liquidity Score @@ -43,7 +42,7 @@ $$LS_{N_{Ask}}$$ follows the same logic as $$LS_{N_{Bid}}$$, but on the ask side $$Spread$$ is calculated from the mid-price[^3] (distance from mid-price divided by mid-price). -For the current values of $$MinDepth$$ and $$MaxSpread$$, see the [Formula Parameters page](formula-parameters.md). +For the current values of $$MinDepth$$ and $$MaxSpread$$, see the [Formula Parameters page](./formula-parameters/). ## Uptime Score @@ -52,7 +51,7 @@ $$ Uptime_{Epoch} = \sum \limits_{N=1}^{40,320} \begin{cases}1&\text{if } \min(LS_{N_{Bid}}, LS_{N_{Ask}}) > 0\\ 0&\text{otherwise} \\\end{cases} $$ -$$Uptime_{Epoch}$$ is the number of order book snapshots throughout the epoch in which the MM[^4] had a [positive Bid Liquidity Score _**and**_ a positive Ask Liquidity Score](./scoring.md#liquidity-score) in the market of interest. This means the MM[^5] quoted on both sides of the order book with order sizes greater than or equal to $$MinDepth$$ with spreads less than or equal to $$MaxSpread$$ in the snapshot. +$$Uptime_{Epoch}$$ is the number of order book snapshots throughout the epoch in which the MM[^4] had a [positive Bid Liquidity Score _**and**_ a positive Ask Liquidity Score](./scoring/#liquidity-score) in the market of interest. This means the MM[^5] quoted on both sides of the order book with order sizes greater than or equal to $$MinDepth$$ with spreads less than or equal to $$MaxSpread$$ in the snapshot. For MMs[^6] who qualify for OLP rewards (for the first time ever) partway through an epoch, $$Uptime_{Epoch}$$ is scaled based on the total number of snapshots from the moment of qualification to the end of the epoch. @@ -89,7 +88,7 @@ LS_{N_{Ask}} = \frac{AskDepth_1}{Spread_1} + \frac{AskDepth_2}{Spread_2} + … \ $$ -For information on individual reward calculations each epoch, see the [Reward Allocations page](reward-allocations.md). +For information on individual reward calculations each epoch, see the [Reward Allocations page](./reward-allocations/). [^1]: Market Maker diff --git a/.gitbook/defi/open-liquidity-program/volatility-response-modifications.mdx b/.gitbook/defi/open-liquidity-program/volatility-response-modifications.mdx index 2fbb66e..66526fe 100644 --- a/.gitbook/defi/open-liquidity-program/volatility-response-modifications.mdx +++ b/.gitbook/defi/open-liquidity-program/volatility-response-modifications.mdx @@ -1,4 +1,6 @@ -# Volatility Response Modifications (VRMs) +--- +title: Volatility Response Modifications (VRMs) +--- Volatility Response Modifications (VRMs) are part of our dynamic rewards system designed to optimise liquidity efficiency across the protocol. These modifications allow us to reallocate rewards when market conditions require adjustment, ensuring that incentives align with the protocol's needs during periods of high volatility. diff --git a/.gitbook/defi/staking.mdx b/.gitbook/defi/staking.mdx index 5d9daa5..d10aef1 100644 --- a/.gitbook/defi/staking.mdx +++ b/.gitbook/defi/staking.mdx @@ -1,4 +1,6 @@ -# Staking +--- +title: Staking +--- ### What is Staking? diff --git a/.gitbook/defi/tokens/cw20-standard.mdx b/.gitbook/defi/tokens/cw20-standard.mdx index 1aae2ee..85ccb8f 100644 --- a/.gitbook/defi/tokens/cw20-standard.mdx +++ b/.gitbook/defi/tokens/cw20-standard.mdx @@ -1,3 +1,5 @@ -# CW20 Standard +--- +title: CW20 Standard +--- The CW20 token standard provides a framework for the permissionless creation and management of fungible tokens that more closely resembles the [ERC20 standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/). As stated above, the TokenFactory is encouraged due to its native integration with the Cosmos SDK, but should you wish to use the CW20 standard for any reason, you can convert CW20 tokens to TokenFactory tokens and vice versa using the [CW20 Adapter](https://github.com/CosmWasm/cw-plus/blob/main/packages/cw20/README.md). For more information regarding the CW20 standard, see its formal specification [here](https://github.com/CosmWasm/cw-plus/blob/main/packages/cw20/README.md). diff --git a/.gitbook/defi/tokens.mdx b/.gitbook/defi/tokens/index.mdx similarity index 97% rename from .gitbook/defi/tokens.mdx rename to .gitbook/defi/tokens/index.mdx index b3adbed..fe2bdf5 100644 --- a/.gitbook/defi/tokens.mdx +++ b/.gitbook/defi/tokens/index.mdx @@ -1,4 +1,6 @@ -# Token Standards +--- +title: Token Standards +--- Injective provides a variety of different token standards one can use when creating a dApp. In this document, we will cover the different types of tokens, as well as recommendations and guidance for using each. @@ -16,4 +18,4 @@ Depending on the origin of the denom and how it was created on Injective, we hav We'll share more details about these denom types later on in this document. -Learn how to get [denom metadata](../../developers/assets/token-metadata.md). +Learn how to get [denom metadata](../../developers/assets/token-metadata/). diff --git a/.gitbook/defi/tokens/inj-coin.mdx b/.gitbook/defi/tokens/inj-coin.mdx index 4165f4e..7794623 100644 --- a/.gitbook/defi/tokens/inj-coin.mdx +++ b/.gitbook/defi/tokens/inj-coin.mdx @@ -1,4 +1,6 @@ -# INJ coin +--- +title: INJ coin +--- INJ is the native asset powering Injective and its broader ecosystem. Each component of INJ is deliberately engineered to cultivate a thriving Web3 ecosystem. As the native asset of the blockchain, INJ plays a central role in facilitating various operations on Injective. Integral to Injective’s custom implementation of the Tendermint Proof-of-Stake (PoS) consensus framework, INJ is crucial for securing the network through staking. Additionally, INJ functions as Injective’s governance token and serves as a means of exchange within the broader Injective ecosystem. Notably, INJ distinguishes itself from other native assets on PoS chains by leveraging core Injective modules to engineer deflationary characteristics through an innovative burn and a dynamic supply mechanism. @@ -61,7 +63,7 @@ The exchange protocol implements a global minimum trading fee of 0.1% for makers The remaining 60% of the exchange fee will undergo an on-chain buy-back-and-burn event where the aggregate exchange fee basket is auctioned off to the highest bidder in exchange for INJ. The INJ proceeds of this auction are then burned, thus deflating the total INJ supply. -More details on the auction mechanism can be found [here](../community-burn.md). +More details on the auction mechanism can be found [here](../community-burn/). #### 6. Backing Collateral for Derivatives diff --git a/.gitbook/defi/tokens/token-factory.mdx b/.gitbook/defi/tokens/token-factory.mdx index 350be90..8b3f6ed 100644 --- a/.gitbook/defi/tokens/token-factory.mdx +++ b/.gitbook/defi/tokens/token-factory.mdx @@ -1,8 +1,11 @@ -# Token Factory +--- +title: Token Factory +--- TokenFactory tokens are tokens that are natively integrated into the bank module of the Cosmos SDK. Their name takes on the format `factory/{creatorAddress}/{subdenom}`. Because tokens are namespaced by the creator address, this allows for permissionless token minting, due to not needing to resolve name collisions. This integration provides support for tracking and querying the total supply of all assets, unlike the CW20 standard, which requires querying the smart contract directly. For this reason, using the TokenFactory standard is recommended. Products such as Helix or Mito, for example, are built on the Injective exchange module, which exclusively uses bank tokens. TokenFactory tokens can be created via the injectived CLI, as well as via smart contract. Tokens bridged into Injective via Wormhole are also TokenFactory tokens. -To learn more about creating your token on Injective, see [token launch](../../developers-defi/token-launch.md). +To learn more about creating your token on Injective, see [token launch](../../developers-defi/token-launch/). + To read more about the TokenFactory standard, see [token factory module](../../developers-native/injective/tokenfactory/). diff --git a/.gitbook/defi/trading.mdx b/.gitbook/defi/trading.mdx deleted file mode 100644 index 9bc4776..0000000 --- a/.gitbook/defi/trading.mdx +++ /dev/null @@ -1,2 +0,0 @@ -# Trading - diff --git a/.gitbook/defi/trading/derivatives-election-perpetual.mdx b/.gitbook/defi/trading/derivatives-election-perpetual.mdx index 0a208f9..3b13bfa 100644 --- a/.gitbook/defi/trading/derivatives-election-perpetual.mdx +++ b/.gitbook/defi/trading/derivatives-election-perpetual.mdx @@ -1,9 +1,8 @@ --- hidden: true +title: Election Perpetual --- -# Election Perpetual - An election perpetual futures contract - or an election perp - is a type of derivative financial instrument on Injective that allows users to gain leveraged exposure to an elections market. An election perp is a perpetual futures contract that tracks the price of a market on Polymarket, rather than a traditional crypto asset. Unlike traditional futures, these contracts don't have an expiry date. They can be held indefinitely. Trades are settled in USDT. LIke other perps, election perps use a funding rate mechanism to keep the contract price close to the underlying index price. @@ -18,7 +17,7 @@ Expiry futures require mark prices to track liquidation and settlement prices. B ### Mark Price Mechanism -The mark price for election perps on Injective is based on a proprietary oracle feed provided by Stork. In the example of the 2024ELECTION PERP, Stork queries the midpoint of [the 2024 Presidential Election market on Polymarket](election-perpetual.md#how-do-election-perpetual-futures-work). They then apply a six-hour time weighted average price (TWAP) to prevent drastic swings in the mark price. That price is then scaled down to a more human readable format (i.e. a price between $0 and $1), and used as the mark price. +The mark price for election perps on Injective is based on a proprietary oracle feed provided by Stork. In the example of the 2024ELECTION PERP, Stork queries the midpoint of the 2024 Presidential Election market on Polymarket. They then apply a six-hour time weighted average price (TWAP) to prevent drastic swings in the mark price. That price is then scaled down to a more human readable format (i.e. a price between $0 and $1), and used as the mark price. ### Market Settlement diff --git a/.gitbook/defi/trading/derivatives-expiry-futures.mdx b/.gitbook/defi/trading/derivatives-expiry-futures.mdx index e5b7026..b6328db 100644 --- a/.gitbook/defi/trading/derivatives-expiry-futures.mdx +++ b/.gitbook/defi/trading/derivatives-expiry-futures.mdx @@ -1,9 +1,8 @@ --- description: Learn about expiry futures on Injective +title: Expiry Futures --- -# Expiry Futures - In TradFi[^1], a futures contract is an agreement that requires two parties to transact an asset at a predetermined price at a specified time in the future. This allows traders to lock in a future price of the underlying asset to hedge or speculate on price movements. Injective offers a completely decentralized form of these futures contracts—expiry futures. Similar to perpetual futures, expiry futures on Injective are traded with margin, allowing traders to access leverage. However, unlike perpetual futures, expiry futures have expiration dates and do not require funding payments, though liquidations may still occur if the maintenance margin threshold is not met. diff --git a/.gitbook/defi/trading/derivatives-iassets.mdx b/.gitbook/defi/trading/derivatives-iassets.mdx index e13eac9..c55a403 100644 --- a/.gitbook/defi/trading/derivatives-iassets.mdx +++ b/.gitbook/defi/trading/derivatives-iassets.mdx @@ -1,4 +1,6 @@ -# iAssets +--- +title: iAssets +--- iAssets are a new class of real-world asset (RWA) derivatives that bring traditional markets - such as equities, commodities, and FX - onto Injective in a fully on-chain, composable, and capital-efficient form. diff --git a/.gitbook/defi/trading/derivatives-index-perpetual-futures.mdx b/.gitbook/defi/trading/derivatives-index-perpetual-futures.mdx index f792aca..e3364d7 100644 --- a/.gitbook/defi/trading/derivatives-index-perpetual-futures.mdx +++ b/.gitbook/defi/trading/derivatives-index-perpetual-futures.mdx @@ -1,4 +1,6 @@ -# Index Perpetual Futures +--- +title: Index Perpetual Futures +--- An index perpetual futures contract, often referred to as an "index perp," is a type of derivative financial instrument commonly used in cryptocurrency markets. An index perp is a perpetual futures contract that tracks the price of an index, rather than a single asset. In the context of cryptocurrencies, this index typically represents a basket of cryptocurrencies or instead - as in the case of the BUIDL/USDT Index Perp - the total supply of a product on chain, as dictated by the token's smart contract. diff --git a/.gitbook/defi/trading/derivatives-perpetuals.mdx b/.gitbook/defi/trading/derivatives-perpetuals.mdx index eb68b48..3a4d163 100644 --- a/.gitbook/defi/trading/derivatives-perpetuals.mdx +++ b/.gitbook/defi/trading/derivatives-perpetuals.mdx @@ -1,9 +1,8 @@ --- description: Learn about perpetual futures on Injective +title: Perpetuals --- -# Perpetuals - We've already established that an expiry futures contract is an agreement requiring two parties to transact an asset at a predetermined price at a specified time in the future, allowing traders to lock in a future price of the underlying asset to hedge or speculate on price movements. Injective offers a completely decentralized form of not only expiry futures, but perpetual futures as well. Perpetual futures on Injective are traded with margin, allowing traders to access leverage. Unlike expiry futures, perpetual futures have no specific expiry date. As such, they require funding payments. In addition, liquidations may occur if the maintenance margin threshold is not met. Perpetual futures are cash-setled, which means the contract is settled in cash rather than delivery of the underlying asset. This makes them more flexible than traditional expiry futures contracts, which have a predetermined expiry date and must be settled by delivering the underlying asset. diff --git a/.gitbook/defi/trading/derivatives-pre-launch-futures.mdx b/.gitbook/defi/trading/derivatives-pre-launch-futures.mdx index ca164a7..f086f0a 100644 --- a/.gitbook/defi/trading/derivatives-pre-launch-futures.mdx +++ b/.gitbook/defi/trading/derivatives-pre-launch-futures.mdx @@ -1,9 +1,8 @@ --- description: Asset speculation before release +title: Pre-Launch Futures --- -# Pre-Launch Futures - Many assets generate large amounts of trading activity when they are publicly launched but are generally unavailable to be traded prior to public release. To capture escalating interest and allow investors to speculate on assets prior to their public release dates, Injective has created Pre-Launch Futures (PLF). The first Pre-Launch Futures market on Injective will be based on an expiry futures contract, though PLFs[^1] can also take the form of a perpetual futures contract. ### How do Pre-Launch Futures Work? diff --git a/.gitbook/defi/trading/derivatives.mdx b/.gitbook/defi/trading/derivatives.mdx index b00a7db..9c9a1be 100644 --- a/.gitbook/defi/trading/derivatives.mdx +++ b/.gitbook/defi/trading/derivatives.mdx @@ -1,2 +1,4 @@ -# Derivatives +--- +title: Derivatives +--- diff --git a/.gitbook/defi/trading/fees.mdx b/.gitbook/defi/trading/fees.mdx index d4fdaf5..28f7dbf 100644 --- a/.gitbook/defi/trading/fees.mdx +++ b/.gitbook/defi/trading/fees.mdx @@ -1,4 +1,6 @@ -# Trading Fees and Rebates +--- +title: Trading Fees and Rebates +--- All trades on Injective are subject to fee rebates, whereby the fee recipient always receives a flat 40% of the trading fee regardless of whether the trade constitutes maker or taker flow. Relayers who originate an order can set the fee recipient. Therefore, if an API trader sets their own address as the fee recipient, that 40% goes to the trader's bank (subaccount 0) address. If the trade is done on Exchange dApps such as Helix, the 40% fee goes to the address that the particular Exchange dApp has set as the fee recipient. diff --git a/.gitbook/defi/trading/index.mdx b/.gitbook/defi/trading/index.mdx new file mode 100644 index 0000000..42cf002 --- /dev/null +++ b/.gitbook/defi/trading/index.mdx @@ -0,0 +1,3 @@ +--- +title: Trading +--- diff --git a/.gitbook/defi/trading/margin-funding-rates.mdx b/.gitbook/defi/trading/margin-funding-rates.mdx index e09f10c..3ba1c4e 100644 --- a/.gitbook/defi/trading/margin-funding-rates.mdx +++ b/.gitbook/defi/trading/margin-funding-rates.mdx @@ -1,4 +1,6 @@ -# Funding Rates +--- +title: Funding Rates +--- While margin trading unlocks the door to amplified gains, it also introduces another layer of complexity - funding requirements. Often overshadowed by margin requirements, understanding funding rates is crucial for responsible leveraged trading on Helix. diff --git a/.gitbook/defi/trading/margin-liquidation.mdx b/.gitbook/defi/trading/margin-liquidation.mdx index d191ed2..a1acc0b 100644 --- a/.gitbook/defi/trading/margin-liquidation.mdx +++ b/.gitbook/defi/trading/margin-liquidation.mdx @@ -1,4 +1,6 @@ -# Liquidation +--- +title: Liquidation +--- Leveraging the power of margin trading comes with the risk of liquidation. This mechanism acts as a failsafe for both the trader and the DEX, automatically closing your position when your equity dips below a critical threshold. This is done to prevent further losses and protect the system's stability. diff --git a/.gitbook/defi/trading/margin-performing-liquidations.mdx b/.gitbook/defi/trading/margin-performing-liquidations.mdx index 4605237..efbd7ba 100644 --- a/.gitbook/defi/trading/margin-performing-liquidations.mdx +++ b/.gitbook/defi/trading/margin-performing-liquidations.mdx @@ -1,4 +1,6 @@ -# Performing Liquidations +--- +title: Performing Liquidations +--- This guide details how traders on Injective can utilize the `MsgLiquidatePosition` function to liquidate underwater positions. diff --git a/.gitbook/defi/trading/margin.mdx b/.gitbook/defi/trading/margin.mdx index 4554daf..cb15a05 100644 --- a/.gitbook/defi/trading/margin.mdx +++ b/.gitbook/defi/trading/margin.mdx @@ -1,4 +1,6 @@ -# Margin Trading +--- +title: Margin Trading +--- Multiple types of futures on Injective involve margin trading, which is defined as using borrowed capital to amplify your potential returns and risks when trading certain futures contracts. However, it's crucial to understand the risks involved before diving in, as margin trading can amplify losses just as easily as gains. diff --git a/.gitbook/defi/trading/order-types.mdx b/.gitbook/defi/trading/order-types.mdx index 1bd2aad..05163eb 100644 --- a/.gitbook/defi/trading/order-types.mdx +++ b/.gitbook/defi/trading/order-types.mdx @@ -1,9 +1,8 @@ --- description: Read about order types on Injective +title: Order Types --- -# Order Types - The following list describes the supported order types on Injective: * **BUY (1):** A standard buy order to purchase an asset at either the current market price or a set limit price. Market orders in Injective also have a price to stablish a limit to the market price the order will be executed with. diff --git a/.gitbook/defi/transaction-fees.mdx b/.gitbook/defi/transaction-fees.mdx index 066a9ca..bd9c8e1 100644 --- a/.gitbook/defi/transaction-fees.mdx +++ b/.gitbook/defi/transaction-fees.mdx @@ -1,4 +1,6 @@ -# Gas and Fees +--- +title: Gas and Fees +--- ## Gas and Fees diff --git a/.gitbook/defi/transactions.mdx b/.gitbook/defi/transactions.mdx index 9983a3d..1c54c0f 100644 --- a/.gitbook/defi/transactions.mdx +++ b/.gitbook/defi/transactions.mdx @@ -1,4 +1,6 @@ -# Transactions +--- +title: Transactions +--- When users want to interact with Injective and make state changes, they create transactions. Once the transaction is created, it requires a signature from the private key linked to the account initiating the particular state change. Following the signature, the transaction is broadcasted to Injective. diff --git a/.gitbook/defi/wallet/accounts.mdx b/.gitbook/defi/wallet/accounts.mdx index 61476c6..4125dd2 100644 --- a/.gitbook/defi/wallet/accounts.mdx +++ b/.gitbook/defi/wallet/accounts.mdx @@ -1,4 +1,6 @@ -# Accounts +--- +title: Accounts +--- This section describes the built-in accounts system of Injective. diff --git a/.gitbook/defi/wallet/create.mdx b/.gitbook/defi/wallet/create.mdx index 8a2c517..61cefab 100644 --- a/.gitbook/defi/wallet/create.mdx +++ b/.gitbook/defi/wallet/create.mdx @@ -1,9 +1,8 @@ --- description: Learn how to create a wallet on Injective using different approaches. +title: Create a wallet --- -# Create a wallet - Creating a wallet on Injective is as simple as sending some funds to your Injective address. In this document we'll outline how to create a wallet using some popular wallet solutions (Metamask, Ledger, etc.), but also how to create and fund a wallet using `injectived` in a local CLI environment. ### Browser Wallets @@ -12,6 +11,6 @@ You can create an Injective wallet using your preferred wallet by following the ### Local Wallets -You can create an Injective wallet for your development purposes using [injectived](../../developers/injectived/ "mention") in a CLI environment. You can do that using the `injectived keys` [command](../../developers/injectived/advanced.md#keys). +You can create an Injective wallet for your development purposes using [injectived](../../developers/injectived/ "mention") in a CLI environment. You can do that using the `injectived keys` [command](../../developers/injectived/advanced/#keys). -You can also learn more about keyring management using `injectived` on this page [set-up-keyring.md](../../infra/set-up-keyring.md "mention") +You can also learn more about keyring management using `injectived` on this page [set-up-keyring.md](../../infra/set-up-keyring/ "mention") diff --git a/.gitbook/defi/wallet.mdx b/.gitbook/defi/wallet/index.mdx similarity index 99% rename from .gitbook/defi/wallet.mdx rename to .gitbook/defi/wallet/index.mdx index bab9d4e..bd8621c 100644 --- a/.gitbook/defi/wallet.mdx +++ b/.gitbook/defi/wallet/index.mdx @@ -1,4 +1,6 @@ -# Wallet +--- +title: Wallet +--- The Injective Wallet allows you to monitor your assets on Injective. Assets can be native tokens on Injective, as well as bridged assets from Ethereum, Solana, Polygon and various IBC-enabled chains. See [Injective Hub Staking Walkthrough](https://injective.com/blog/injective-hub/) diff --git a/.gitbook/developers-cosmwasm/cosmwasm-any.mdx b/.gitbook/developers-cosmwasm/cosmwasm-any.mdx index 50168a5..c9f28e1 100644 --- a/.gitbook/developers-cosmwasm/cosmwasm-any.mdx +++ b/.gitbook/developers-cosmwasm/cosmwasm-any.mdx @@ -1,4 +1,6 @@ -# Using Injective Modules and Queries in CosmWasm +--- +title: Using Injective Modules and Queries in CosmWasm +--- This guide provides a comprehensive overview of how to interact with Injective's modules and queries in CosmWasm using `Any` messages and queries. The older [injective-cosmwasm](https://github.com/InjectiveLabs/cw-injective/tree/dev/packages/injective-cosmwasm) package, which relied on JSON-encoded messages, is no longer maintained and may become outdated. This guide focuses on the recommended approach using protobuf-encoded `Any` messages and queries, which is more efficient and aligned with modern CosmWasm standards. diff --git a/.gitbook/developers-cosmwasm/create-uis-guide.mdx b/.gitbook/developers-cosmwasm/create-uis-guide.mdx index 3c24845..8edfb3a 100644 --- a/.gitbook/developers-cosmwasm/create-uis-guide.mdx +++ b/.gitbook/developers-cosmwasm/create-uis-guide.mdx @@ -1,7 +1,9 @@ -# Creating UIs +--- +title: Creating UIs +--- -More comprehensive docs about creating UIs as well as bootstrapping options can be found on the [dApps docs](../developers/dapps/README.md). +More comprehensive docs about creating UIs as well as bootstrapping options can be found on the [dApps docs](../developers/dapps/). We've interacted with our contract through the Injective CLI, but this is not ideal for most dApp users. A web UI can provide a much better experience! Rather than sending transaction messages through `injectived`, we can abstract away the complexity and provide the user with two buttons—one to increment the count, and one to reset the count. @@ -15,5 +17,5 @@ Now, interacting with the contract is as simple as clicking a button and signing ![](https://docs.injective.network/img/metamask_select_testnet.png) -You may notice that you get an "Unauthorized" error message when attempting to reset the count. This is expected behavior! Recall from the [contract logic for reset](./smart-contracts/your-first-smart-contract.md#reset) that only the contract owner is permitted to reset the count. Since you did not instantiate the exact contract that the frontend is interacting with, you don't have the required permissions to reset the count. +You may notice that you get an "Unauthorized" error message when attempting to reset the count. This is expected behavior! Recall from the [contract logic for reset](./smart-contracts/your-first-smart-contract/#reset) that only the contract owner is permitted to reset the count. Since you did not instantiate the exact contract that the frontend is interacting with, you don't have the required permissions to reset the count. diff --git a/.gitbook/developers-cosmwasm/create-your-swap-contract-guide.mdx b/.gitbook/developers-cosmwasm/create-your-swap-contract-guide.mdx index cf7be61..ec7eff4 100644 --- a/.gitbook/developers-cosmwasm/create-your-swap-contract-guide.mdx +++ b/.gitbook/developers-cosmwasm/create-your-swap-contract-guide.mdx @@ -1,4 +1,6 @@ -# Create your Swap Contract +--- +title: Create your Swap Contract +--- The [swap contract](https://github.com/InjectiveLabs/swap-contract) allows an instant swap between two different tokens. Under the hood, it uses atomic orders to place market orders in one or more spot markets. diff --git a/.gitbook/developers-cosmwasm/cw20-adapter.mdx b/.gitbook/developers-cosmwasm/cw20-adapter.mdx index 07a871d..e34221d 100644 --- a/.gitbook/developers-cosmwasm/cw20-adapter.mdx +++ b/.gitbook/developers-cosmwasm/cw20-adapter.mdx @@ -1,4 +1,6 @@ -# CW20 Adapter +--- +title: CW20 Adapter +--- In this document, we'll explain the CW20 Adapter Contract that allows exchanging CW-20 tokens for Injective issued native tokens (using the TokenFactory module) and vice versa. For the CW-20 Adapter GitHub repository, see [here](https://github.com/InjectiveLabs/cw20-adapter/tree/master/contracts/cw20-adapter). diff --git a/.gitbook/developers-cosmwasm.mdx b/.gitbook/developers-cosmwasm/index.mdx similarity index 94% rename from .gitbook/developers-cosmwasm.mdx rename to .gitbook/developers-cosmwasm/index.mdx index 4f9fe22..0e75d48 100644 --- a/.gitbook/developers-cosmwasm.mdx +++ b/.gitbook/developers-cosmwasm/index.mdx @@ -1,9 +1,7 @@ --- - +title: Cosmwasm Developers --- -# Cosmwasm Developers - CosmWasm is a novel smart contracting platform built for the Cosmos ecosystem. You can learn more about CosmWasm from [the CosmWasm docs](https://cosmwasm.cosmos.network/), or see the [CosmWasm Book](https://book.cosmwasm.com/index.html) for a guide on creating CosmWasm smart contracts. **Start your builder journey on Injective using Cosmwasm here**: [Your First CosmWasm Smart Contracts](./smart-contracts/your-first-smart-contract.md "mention") diff --git a/.gitbook/developers-cosmwasm/injective-test-tube.mdx b/.gitbook/developers-cosmwasm/injective-test-tube.mdx index 0d14cf5..a2dbd3c 100644 --- a/.gitbook/developers-cosmwasm/injective-test-tube.mdx +++ b/.gitbook/developers-cosmwasm/injective-test-tube.mdx @@ -1,4 +1,6 @@ -# Injective Test Tube +--- +title: Injective Test Tube +--- `injective-test-tube` is a CosmWasm x Injective integration testing library that, unlike `cw-multi-test`, allows you to test your CosmWasm contract against the chain's actual logic instead of mocks. diff --git a/.gitbook/developers-cosmwasm/local-development-guide.mdx b/.gitbook/developers-cosmwasm/local-development-guide.mdx index 5a952aa..42f3201 100644 --- a/.gitbook/developers-cosmwasm/local-development-guide.mdx +++ b/.gitbook/developers-cosmwasm/local-development-guide.mdx @@ -1,4 +1,6 @@ -# Local Development +--- +title: Local Development +--- This guide will get you started deploying `cw20` smart contracts on a local Injective network running on your computer. @@ -29,9 +31,9 @@ cargo install cargo-generate ### injectived -Make sure you have `injectived` installed locally. You can follow the [install-injectived.md](../developers/injectived/install.md "mention")guide to get `injectived` and other prerequisites running locally. +Make sure you have `injectived` installed locally. You can follow the [install-injectived.md](../developers/injectived/install/ "mention")guide to get `injectived` and other prerequisites running locally. -Once you have `injectived` installed, you should also [start a local chain instance.](..//developers/injectived/install.md#start-injectived) +Once you have `injectived` installed, you should also [start a local chain instance.](..//developers/injectived/install/#start-injectived) ### Compile CosmWasm Contracts @@ -454,4 +456,4 @@ Here are the main differences between a `local` and `testnet` development/deploy * Instead of using `injective-1` as a `chainId` you should use `injective-888` i.e the `chain-id` flag should now be `--chain-id="injective-888"` * You can use the [Injective Testnet Explorer](https://testnet.explorer.injective.network/smart-contracts/code/) to find information about the `codeId` of the uploaded smart contracts OR find your instantiated smart contract -You can read more on the `injectived` and how to use it to query/send transactions against `testnet` [using-injectived.md](../developers/injectived/use.md "mention"). +You can read more on the `injectived` and how to use it to query/send transactions against `testnet` [using-injectived.md](../developers/injectived/use/ "mention"). diff --git a/.gitbook/developers-cosmwasm/mainnet-deployment-guide.mdx b/.gitbook/developers-cosmwasm/mainnet-deployment-guide.mdx index a237344..823b1c4 100644 --- a/.gitbook/developers-cosmwasm/mainnet-deployment-guide.mdx +++ b/.gitbook/developers-cosmwasm/mainnet-deployment-guide.mdx @@ -1,4 +1,6 @@ -# Mainnet Deployment +--- +title: Mainnet Deployment +--- This guide will get you started with the governance process of deploying and instantiating CosmWasm smart contracts on Injective Mainnet. diff --git a/.gitbook/developers-cosmwasm/smart-contracts/cw20-convert-market-order.mdx b/.gitbook/developers-cosmwasm/smart-contracts/cw20-convert-market-order.mdx index 0a674f7..a78ea11 100644 --- a/.gitbook/developers-cosmwasm/smart-contracts/cw20-convert-market-order.mdx +++ b/.gitbook/developers-cosmwasm/smart-contracts/cw20-convert-market-order.mdx @@ -1,6 +1,8 @@ -# CW20 to Bank & Market Order in One Transaction +--- +title: CW20 to Bank & Market Order in One Transaction +--- -This example helps you create messages to convert CW20 tokens to bank tokens on the Injective blockchain. This is particularly useful when you have CW20 tokens and need to convert them to their bank equivalents to perform operations like placing market orders. Note that this flow only works for cw20 tokens and their corresponding [factory tokens](../../developers/concepts/README.md). +This example helps you create messages to convert CW20 tokens to bank tokens on the Injective blockchain. This is particularly useful when you have CW20 tokens and need to convert them to their bank equivalents to perform operations like placing market orders. Note that this flow only works for cw20 tokens and their corresponding [factory tokens](../../developers/concepts/). This guide will walk you through: @@ -10,17 +12,17 @@ This guide will walk you through: ## Get User's CW20 Balance -You can perform this using [explorer indexer queries](../../developers-native/query-indexer/explorer.md#fetch-cw20-balances). +You can perform this using [explorer indexer queries](../../developers-native/query-indexer/explorer/#fetch-cw20-balances). * Find the cw20 address and balance from the result set that you want to convert to a bank factory token ## Create CW20 to Bank Conversion Message -* create the `convertMsg` using the steps detailed [here](../../developers/concepts/token-factory.md#example-on-how-to-convert-cw20-to-a-factory-denom) in order to convert your CW20 token to a bank factory token. No need to submit the tsx yet. +* create the `convertMsg` using the steps detailed [here](../../developers/concepts/token-factory/#example-on-how-to-convert-cw20-to-a-factory-denom) in order to convert your CW20 token to a bank factory token. No need to submit the tsx yet. ## Create a `MsgCreateSpotMarketOrder` message -* Create the `msg` using the steps detailed in [MsgCreateSpotMarketOrder](../../developers-native/examples/exchange.md#msgcreatespotmarketorder). No need to submit the tsx yet. +* Create the `msg` using the steps detailed in [MsgCreateSpotMarketOrder](../../developers-native/examples/exchange/#msgcreatespotmarketorder). No need to submit the tsx yet. * Note that the buy order you create will have access to your converted cw20 balance + existing bank balance. Example: ```ts diff --git a/.gitbook/developers-cosmwasm/smart-contracts.mdx b/.gitbook/developers-cosmwasm/smart-contracts/index.mdx similarity index 72% rename from .gitbook/developers-cosmwasm/smart-contracts.mdx rename to .gitbook/developers-cosmwasm/smart-contracts/index.mdx index 8549bb9..b2881b1 100644 --- a/.gitbook/developers-cosmwasm/smart-contracts.mdx +++ b/.gitbook/developers-cosmwasm/smart-contracts/index.mdx @@ -1,4 +1,6 @@ -# CosmWasm Smart Contracts +--- +title: CosmWasm Smart Contracts +--- ## What is CosmWasm? @@ -7,12 +9,12 @@ CosmWasm is a novel smart contracting platform built for the Cosmos ecosystem. Y ## Developing CosmWasm Smart Contracts New to CosmWasm? -We suggest that you follow this guide: [Your First CosmWasm Smart Contract](./your-first-smart-contract.md) +We suggest that you follow this guide: [Your First CosmWasm Smart Contract](./your-first-smart-contract/) ## Notable Cosmwasm Smart Contracts | Topic | Description | | ------------------------------------------------------------------------------------------ | ---------------------- | -| [Injective Name Service](injective-name-service.md) | Injective Name Service | -| [Neptune Service](neptune-service.md) | Neptune Service | -| [CW20 to Bank & Market Order in One Transaction](cw20-convert-market-order.md) | Convert Cw20 Example | +| [Injective Name Service](./injective-name-service/) | Injective Name Service | +| [Neptune Service](./neptune-service/) | Neptune Service | +| [CW20 to Bank & Market Order in One Transaction](./cw20-convert-market-order/) | Convert Cw20 Example | diff --git a/.gitbook/developers-cosmwasm/smart-contracts/injective-name-service.mdx b/.gitbook/developers-cosmwasm/smart-contracts/injective-name-service.mdx index 3f5a89c..488b23d 100644 --- a/.gitbook/developers-cosmwasm/smart-contracts/injective-name-service.mdx +++ b/.gitbook/developers-cosmwasm/smart-contracts/injective-name-service.mdx @@ -1,4 +1,6 @@ -# Injective Name Service +--- +title: Injective Name Service +--- Within this section, we will look at how to query the Injective name service contracts. diff --git a/.gitbook/developers-cosmwasm/smart-contracts/neptune-service.mdx b/.gitbook/developers-cosmwasm/smart-contracts/neptune-service.mdx index 13b3900..fe3aa29 100644 --- a/.gitbook/developers-cosmwasm/smart-contracts/neptune-service.mdx +++ b/.gitbook/developers-cosmwasm/smart-contracts/neptune-service.mdx @@ -1,4 +1,6 @@ -# NeptuneService +--- +title: NeptuneService +--- `NeptuneService` is a straightforward tool that interacts with the Neptune CosmWasm smart contracts on Injective. It allows you to fetch asset prices, calculate exchange ratios, create deposit and withdraw messages, and retrieve lending rates. diff --git a/.gitbook/developers-cosmwasm/smart-contracts/your-first-smart-contract.mdx b/.gitbook/developers-cosmwasm/smart-contracts/your-first-smart-contract.mdx index c5d5adc..e008a64 100644 --- a/.gitbook/developers-cosmwasm/smart-contracts/your-first-smart-contract.mdx +++ b/.gitbook/developers-cosmwasm/smart-contracts/your-first-smart-contract.mdx @@ -1,4 +1,6 @@ -# Your First CosmWasm Smart Contract +--- +title: Your First CosmWasm Smart Contract +--- Within this section, we'll explain how to setup your environment for CosmWasm Smart Contracts Development. @@ -406,7 +408,7 @@ Alternatively, a Docker image has been prepared to make this tutorial easier. If you install `injectived` from the binary, ignore the docker commands. -In the [public endpoints section](../../infra/public-endpoints.md) you can find the right --node info to interact with Mainnet and Testnet. +In the [public endpoints section](../../infra/public-endpoints/) you can find the right --node info to interact with Mainnet and Testnet. Executing this command will make the docker container execute indefinitely. @@ -478,7 +480,7 @@ curl -X GET "https://sentry.testnet.lcd.injective.network/cosmos/bank/v1beta1/ba ## Upload the Wasm Contract -Now it's time to upload the `.wasm` file that you compiled in the previous steps to the Injective Testnet. Please note that the procedure for mainnet is different and [requires a governance proposal.](../mainnet-deployment-guide.md) +Now it's time to upload the `.wasm` file that you compiled in the previous steps to the Injective Testnet. Please note that the procedure for mainnet is different and [requires a governance proposal.](../mainnet-deployment-guide/) ```bash # inside the "injective-core-staging" container, or from the contract directory if running injectived locally diff --git a/.gitbook/developers-cosmwasm/whitelisting-deployment-address-guide.mdx b/.gitbook/developers-cosmwasm/whitelisting-deployment-address-guide.mdx index a68cbee..e14ec91 100644 --- a/.gitbook/developers-cosmwasm/whitelisting-deployment-address-guide.mdx +++ b/.gitbook/developers-cosmwasm/whitelisting-deployment-address-guide.mdx @@ -1,6 +1,8 @@ -# Whitelisting deployment address +--- +title: Whitelisting deployment address +--- -Contract upload on Injective mainnet requires governance approval. You can read through the guide to do so in the [mainnet-deployment.md](./mainnet-deployment-guide.md "mention") guide. +Contract upload on Injective mainnet requires governance approval. You can read through the guide to do so in the [mainnet-deployment.md](./mainnet-deployment-guide/ "mention") guide. This structure has been put in place for multiple reasons: diff --git a/.gitbook/developers-defi/calculate-min-price-tick-size.mdx b/.gitbook/developers-defi/calculate-min-price-tick-size.mdx index 10ccbfe..353129c 100644 --- a/.gitbook/developers-defi/calculate-min-price-tick-size.mdx +++ b/.gitbook/developers-defi/calculate-min-price-tick-size.mdx @@ -1,4 +1,6 @@ -# Min Price Tick Size +--- +title: Min Price Tick Size +--- ## Minimum Market Price Tick Size @@ -36,4 +38,4 @@ To convert back to a human-readable format: $$\text{humanReadableFormat} = \text{value} \times 10^{-\text{quoteDecimals}}$$ -Also, be sure to check out our [concepts](../developers/concepts/calculation-min-price-tick-size.md). +Also, be sure to check out our [concepts](../developers/concepts/calculation-min-price-tick-size/). diff --git a/.gitbook/developers-defi/denom-and-bank.mdx b/.gitbook/developers-defi/denom-and-bank.mdx index 6c0840e..f218342 100644 --- a/.gitbook/developers-defi/denom-and-bank.mdx +++ b/.gitbook/developers-defi/denom-and-bank.mdx @@ -1,4 +1,6 @@ -# Denom Metadata +--- +title: Denom Metadata +--- A `denom` is how tokens are represented within the `Bank` module of Injective. These assets can be used for trading, creating new markets on the exchange module, participating in auctions, transferring to another address, etc. @@ -8,7 +10,7 @@ This guide shows how to fetch `denom` metadata directly from the `injective-list ## Injective Lists -`injective-lists` is a public repository that holds metadata information for all tokens on Injective. It's the most up-to-date and reliable source of this particular information. You can submit your token information by creating a PR for this repo. Be sure to correctly specify the fields. In particular, `"denom"` field (read about [token standards](../defi/tokens/README.md)) should have respective `ibc`, `peggy` and `factory` prefixes depending on the token standard. +`injective-lists` is a public repository that holds metadata information for all tokens on Injective. It's the most up-to-date and reliable source of this particular information. You can submit your token information by creating a PR for this repo. Be sure to correctly specify the fields. In particular, `"denom"` field (read about [token standards](../defi/tokens/)) should have respective `ibc`, `peggy` and `factory` prefixes depending on the token standard. The metadata is fetched automatically for new `denoms` on chain every 30 minutes and the `json` files are regenerated. diff --git a/.gitbook/developers-defi.mdx b/.gitbook/developers-defi/index.mdx similarity index 93% rename from .gitbook/developers-defi.mdx rename to .gitbook/developers-defi/index.mdx index 51a8741..63f8189 100644 --- a/.gitbook/developers-defi.mdx +++ b/.gitbook/developers-defi/index.mdx @@ -1,9 +1,7 @@ --- - +title: DeFi Developers --- -# DeFi Developers - Injective marks the forefront of exchange-focused layer-1 blockchains offering decentralized perpetual swaps, futures, and spot trading. It fully taps into the possibilities of decentralized derivatives and borderless DeFi. Every component is designed to embody complete trustlessness, resistance to censorship, public verifiability, and resilience against front-running. Injective enables traders to create and trade arbitrary spot and derivatives markets. Injective also enables on-chain limit orderbook management, on-chain trade execution, on-chain order matching, on-chain transaction settlement, and on-chain trading incentive distribution through the logic codified by the Injective Chain's [Exchange Module](../developers-native/injective/exchange/). @@ -16,4 +14,4 @@ The goal of Injective's incentive mechanism is to allow exchanges competing amon An exchange can easily set up a client (such as a UI on web or mobile) and an API provider. -Head to our [DEX tutorial](../developers/dapps/example-dex.md) bootstrap your with few clicks! +Head to our [DEX tutorial](../developers/dapps/example-dex/) bootstrap your with few clicks! diff --git a/.gitbook/developers-defi/market-launch.mdx b/.gitbook/developers-defi/market-launch.mdx index 2030374..f282df2 100644 --- a/.gitbook/developers-defi/market-launch.mdx +++ b/.gitbook/developers-defi/market-launch.mdx @@ -1,7 +1,9 @@ -# Launch a Market +--- +title: Launch a Market +--- -The prerequisite for launching a market is to [launch-a-token.md](./token-launch.md "mention") +The prerequisite for launching a market is to [launch-a-token.md](./token-launch/ "mention") Launching a trading pair on Injective is quick, easy, and best of all, permissionless! @@ -12,15 +14,15 @@ For an Injective-native token, skip the bridging portion and head straight to st 1. Navigate to the [Injective Bridge](http://bridge.injective.network/) to begin the process of bridging your chosen ERC-20 token from Ethereum to Injective using the Peggy bridge. -![Injective Bridge](<../.gitbook/assets/Docs - Deposit Peggy.png>) +![Injective Bridge]() 2. Click the dropdown, scroll to the bottom, and click "add" next to the advanced tool to add a custom ERC-20 token using the token address, which you may want to verify on a trusted source like CoinGecko. -![Add Custom ERC-20 Token](<../.gitbook/assets/Docs - Deposit From.png>) +![Add Custom ERC-20 Token]() 3. Copy and paste the correct contract address, and click "add." -![Add Smart Contract Address](<../.gitbook/assets/Docs - Add and Bridge ERC20.png>) +![Add Smart Contract Address]() 4. Now enter the desired amount of the ERC-20 token you wish to bridge, click "approve," confirm the transaction, then click "review," confirm the transaction, and wait. @@ -28,16 +30,16 @@ For an Injective-native token, skip the bridging portion and head straight to st 5. Once the approve spend and deposit transactions are confirmed on the Ethereum blockchain, you will see the progress of the bridging transaction. Once the transaction is confirmed on Injective, your bridged ERC-20 token will be available in your Injective wallet. (Note, if you used MetaMask with the source chain, by default your bridged tokens will be sent to the inj address linked to your MetaMask. This can be changed by clicking the lock icon next to the recipient address at the beginning of step 4.) -![Bridging Completion](<../.gitbook/assets/Docs - Transaction Submitted.png>) +![Bridging Completion]() 6. After the bridging transaction is complete, you're able to list the token permissionlessly on Injective by navigating to the [Injective Hub](https://injhub.com/proposal/create/). -![List on Injective](<../.gitbook/assets/Docs - New Proposal.png>) +![List on Injective]() 7. Choose "instant spot market launch" from the first dropdown, and specify a ticker. In this example, let's use PEPE/INJ. Now pick the base token from the dropdown. However, beware, several tokens might exist under the same ticker. Always match the correct token address. In this case, as the token was bridged using the Peggy bridge, the address will be peggy followed by the ERC-20 contract address. -![Specify Ticker](<../.gitbook/assets/Docs - Select Ticker.png>) +![Specify Ticker]() 8. Now select the correct quote denom, in this case, inj. (Note, if you wish to pair the token with USDT, make sure to select the "correct" USDT address, which is peggy followed by the ERC-20 contract address for USDT.) Finally, specify a minimum price tick size and minimum quantity tick size. Because PEPE/INJ would trade at a fraction of a penny, the minimum ticks are set accordingly. -![Select Quote Denom](<../.gitbook/assets/Docs - Quote Denom.png>) +![Select Quote Denom]() diff --git a/.gitbook/developers-defi/min-quantity-tick-size.mdx b/.gitbook/developers-defi/min-quantity-tick-size.mdx index bf88add..5246182 100644 --- a/.gitbook/developers-defi/min-quantity-tick-size.mdx +++ b/.gitbook/developers-defi/min-quantity-tick-size.mdx @@ -1,4 +1,6 @@ -# Min Quantity Tick Size +--- +title: Min Quantity Tick Size +--- ## Minimum Market Quantity Tick Size @@ -22,4 +24,4 @@ To convert back to a human-readable format: $$\text{humanReadableFormat} = \text{value} \times 10^{-\text{baseDecimals}}$$ -Also, be sure to check out our [concepts](../developers/concepts/calculation-min-price-tick-size.md). +Also, be sure to check out our [concepts](../developers/concepts/calculation-min-price-tick-size/). diff --git a/.gitbook/developers-defi/provider-oracle.mdx b/.gitbook/developers-defi/provider-oracle.mdx index d1f1f8c..770c73e 100644 --- a/.gitbook/developers-defi/provider-oracle.mdx +++ b/.gitbook/developers-defi/provider-oracle.mdx @@ -1,10 +1,12 @@ -# Provider Oracle +--- +title: Provider Oracle +--- Prerequisite reading [Injective Oracle Module](../developers-native/injective/oracle/) -The goal of this section is to provide users a guide on how to launch and maintain an oracle provider on Injective. These oracles can be used for various purposes, like Perpetual Markets, Expiry Futures Markets, [Binary Options markets](../developers-native/injective/exchange/02_binary_options_markets.md), etc. +The goal of this section is to provide users a guide on how to launch and maintain an oracle provider on Injective. These oracles can be used for various purposes, like Perpetual Markets, Expiry Futures Markets, [Binary Options markets](../developers-native/injective/exchange/02_binary_options_markets/), etc. First, what is an oracle provider? It's an oracle **TYPE** that allows external parties to relay price feeds to the Injective chain. These external parties are called providers. A provider identifies each external party, and all the price feeds provided on the chain are stored under that particular provider. This allows custom price feeds to be created on Injective, which can power creative and advanced markets being launched on Injective. diff --git a/.gitbook/developers-defi/testnet-faucet-integration.mdx b/.gitbook/developers-defi/testnet-faucet-integration.mdx index efebbbe..23d73a6 100644 --- a/.gitbook/developers-defi/testnet-faucet-integration.mdx +++ b/.gitbook/developers-defi/testnet-faucet-integration.mdx @@ -1,4 +1,6 @@ -# Testnet Faucet Integration +--- +title: Testnet Faucet Integration +--- If you want to have a testnet faucet integration within your dApp, the only thing you need to do is do a `POST` request to `` `https://jsbqfdd4yk.execute-api.us-east-1.amazonaws.com/v1/faucet` `` and pass an `{ address: inj1...}` as the body of the `POST` request. The address is then stored within the queue ,which is processed every 5 to 10 minutes. diff --git a/.gitbook/developers-defi/token-launch.mdx b/.gitbook/developers-defi/token-launch.mdx index 737a07c..3f67531 100644 --- a/.gitbook/developers-defi/token-launch.mdx +++ b/.gitbook/developers-defi/token-launch.mdx @@ -1,4 +1,6 @@ -# Launch a Token +--- +title: Launch a Token +--- Within this document, we'll explain how to launch a token on Injective. @@ -6,9 +8,9 @@ There are two options for launching a token on Injective: bridging an existing t ## Bridging -The easiest way to launch a token on Injective is by bridging your existing assets from one of the supported networks that Injective is interoperable with. There are guides in the [bridge](../defi/bridge/README.md "mention") sections that you can reference to bridge assets from other networks to Injective. +The easiest way to launch a token on Injective is by bridging your existing assets from one of the supported networks that Injective is interoperable with. There are guides in the [bridge](../defi/bridge/ "mention") sections that you can reference to bridge assets from other networks to Injective. -Once the bridging process is completed, a token will be created on Injective, which you can then use to [launch-a-market.md](./market-launch.md "mention"). +Once the bridging process is completed, a token will be created on Injective, which you can then use to [launch a market](./market-launch/ "mention"). ## Creating a New Token @@ -22,7 +24,7 @@ The [Injective Hub](https://injhub.com/token-factory/) web app provides you the The [TokenStation](https://www.tokenstation.app/) web app provides you the ability to create and manage tokens seamlessly, creating a market on Injective's [native orderbook](../developers-native/injective/exchange/), launching an airdrop, and much more. -### Using DojoSwap[​](../developers-defi/token-launch.md#4-via-dojoswap) +### Using DojoSwap[​](../developers-defi/token-launch/#4-via-dojoswap) Similar to above, you can utilize [DojoSwap's Market Creation module](https://docs.dojo.trading/introduction/market-creation) to create, manage, and list your token, along with several other useful features. diff --git a/.gitbook/developers-evm.mdx b/.gitbook/developers-evm.mdx deleted file mode 100644 index e0929fa..0000000 --- a/.gitbook/developers-evm.mdx +++ /dev/null @@ -1,13 +0,0 @@ ---- - ---- - -# EVM Developers - -Welcome, EVM developers! Native EVM support on Injective lets you deploy Solidity smart contracts. It also opens up possibilities such as interacting with the exchange module, building dApps, and much more. You can now build in Injective with familiar tools, libraries, and workflows! - -## Start Building on EVM - -
Configure Your Networknetwork-information.md
Deploy a ContractBroken link
Precompilesprecompiles.md
Request EVM Testnet Fundshttps://testnet.faucet.injective.network/
- -
Next →Broken link
diff --git a/.gitbook/developers-evm/bank-precompile.mdx b/.gitbook/developers-evm/bank-precompile.mdx index 7b4ff97..936ee66 100644 --- a/.gitbook/developers-evm/bank-precompile.mdx +++ b/.gitbook/developers-evm/bank-precompile.mdx @@ -1,4 +1,6 @@ -# Bank Precompile +--- +title: Bank Precompile +--- The Bank precompile allows smart contracts to interact directly with the `x/bank` module, effectively bringing ERC-20 tokens on-chain. Any ERC-20 contract using the Bank precompile will be represented as `erc20:0x...` denom on-chain. Technically, this means that tokens reside only on-chain, with the EVM providing a view to the chain state rather than maintaining a separate copy. Unlike traditional bridging, where two token versions require user actions to switch, the Bank precompile offers real-time, dual-environment reflection for any transfer using either the on-chain bank denom or the ERC-20 `transfer()` method. diff --git a/.gitbook/developers-evm/dapps/connect-with-metamask.mdx b/.gitbook/developers-evm/dapps/connect-with-metamask.mdx index afe4331..d09eb69 100644 --- a/.gitbook/developers-evm/dapps/connect-with-metamask.mdx +++ b/.gitbook/developers-evm/dapps/connect-with-metamask.mdx @@ -1,4 +1,6 @@ -# Connect with MetaMask +--- +title: Connect with MetaMask +--- ## Connect MetaMask to Injective EVM Testnet @@ -101,9 +103,7 @@ export async function connectMetaMask() { ### Using `ethers.js` to interact with your smart contract -Sample code - -[counter contract](broken-reference) ABI: +Sample code for counter contract ABI: ```tsx // abi/counterAbi.ts diff --git a/.gitbook/developers-evm/dapps/connect-with-walletconnect.mdx b/.gitbook/developers-evm/dapps/connect-with-walletconnect.mdx index 6011e7d..2e39ca1 100644 --- a/.gitbook/developers-evm/dapps/connect-with-walletconnect.mdx +++ b/.gitbook/developers-evm/dapps/connect-with-walletconnect.mdx @@ -1,4 +1,6 @@ -# Connect with WalletConnect +--- +title: Connect with WalletConnect +--- WalletConnect is an open-source, chain-agnostic protocol that securely links wallets and Web3 applications. It uses a bridge server to relay encrypted messages, allowing users to connect by scanning a QR code or via deep-linking, without exposing private keys. diff --git a/.gitbook/developers-evm/dapps.mdx b/.gitbook/developers-evm/dapps/index.mdx similarity index 67% rename from .gitbook/developers-evm/dapps.mdx rename to .gitbook/developers-evm/dapps/index.mdx index d9ce9ab..68b413a 100644 --- a/.gitbook/developers-evm/dapps.mdx +++ b/.gitbook/developers-evm/dapps/index.mdx @@ -1,17 +1,16 @@ --- description: Connect your wallet with MetaMask or WalletConnect +title: Your First EVM dApp --- -# Your First EVM dApp - dApps are front end applications that interact with a blockchain, typically with smart contracts. -Do check out [your first EVM smart contract](../smart-contracts/README.md) first! +Do check out [your first EVM smart contract](../smart-contracts/) first! These guides show you how to connect uisng different EVM wallets and libraries. ## Guides -* [Connect with MetaMask](./connect-with-metamask.md) -* [Connect with WalletConnect](./connect-with-walletconnect.md) +* [Connect with MetaMask](./connect-with-metamask/) +* [Connect with WalletConnect](./connect-with-walletconnect/) diff --git a/.gitbook/developers-evm/erc20-module.mdx b/.gitbook/developers-evm/erc20-module.mdx index 28e0bb3..e65330e 100644 --- a/.gitbook/developers-evm/erc20-module.mdx +++ b/.gitbook/developers-evm/erc20-module.mdx @@ -1,4 +1,6 @@ -# ERC20 Module +--- +title: ERC20 Module +--- ### ERC20 Module diff --git a/.gitbook/developers-evm/evm-equivalence.mdx b/.gitbook/developers-evm/evm-equivalence.mdx index be855b4..6b649cc 100644 --- a/.gitbook/developers-evm/evm-equivalence.mdx +++ b/.gitbook/developers-evm/evm-equivalence.mdx @@ -1,9 +1,8 @@ --- description: Understanding EVM equivalence on Injective +title: EVM Equivalence --- -# EVM Equivalence - ## Injective EVM vs. Ethereum Mainnet Injective's native EVM us a fully embedded execution environment that has been integrated into the core architecture of the chain. It is designed to be a 1:1 equivalent to Ethereum in terms of development experience. @@ -33,4 +32,3 @@ Native EVM on Injective supports the latest version of `geth`, ensuring that dev ## EIP-1559 Configuration Coming soon. - diff --git a/.gitbook/developers-evm/exchange-precompile.mdx b/.gitbook/developers-evm/exchange-precompile.mdx index 4ab5372..42345ab 100644 --- a/.gitbook/developers-evm/exchange-precompile.mdx +++ b/.gitbook/developers-evm/exchange-precompile.mdx @@ -1,4 +1,6 @@ -# Exchange Precompile +--- +title: Exchange Precompile +--- The Exchange Precompile is a system smart contract residing at the fixed address `0x0000000000000000000000000000000000000065`. It offers Solidity developers a gas-efficient and native pathway to interact directly with the Injective chain's exchange module. By leveraging this precompile, your smart contracts can seamlessly perform a variety of exchange-related actions, including: diff --git a/.gitbook/developers-evm/index.mdx b/.gitbook/developers-evm/index.mdx new file mode 100644 index 0000000..10155f5 --- /dev/null +++ b/.gitbook/developers-evm/index.mdx @@ -0,0 +1,46 @@ +--- +title: EVM Developers +--- + +Welcome, EVM developers! Native EVM support on Injective lets you deploy Solidity smart contracts. It also opens up possibilities such as interacting with the exchange module, building dApps, and much more. You can now build in Injective with familiar tools, libraries, and workflows! + +## Start Building on EVM + + + + Set up your connection to Injective's EVM + + + Write **Solidity**. Then compile, test, deploy, verify, and interact with **smart contracts**. + + + EVM interface that allows smart contracts to interact with native functions of the Injective chain + + + INJ Faucet + + diff --git a/.gitbook/developers-evm/infrastructure-and-tooling.mdx b/.gitbook/developers-evm/infrastructure-and-tooling.mdx index e6927c2..bf50c32 100644 --- a/.gitbook/developers-evm/infrastructure-and-tooling.mdx +++ b/.gitbook/developers-evm/infrastructure-and-tooling.mdx @@ -1,9 +1,8 @@ --- description: Build on Injective with World-Class Infrastructure +title: Infrastructure & Tooling --- -# Infrastructure & Tooling - BlockScoutInjective is supported by a rich ecosystem of industry-leading infrastructure providers. Access reliable RPCs, powerful data indexers, and all the tools you need to build and scale your dApp on the fastest L1 for finance. ### RPC & Node Providers diff --git a/.gitbook/developers-evm/multivm-token-standard.mdx b/.gitbook/developers-evm/multivm-token-standard.mdx index 3b10c18..8bc6c95 100644 --- a/.gitbook/developers-evm/multivm-token-standard.mdx +++ b/.gitbook/developers-evm/multivm-token-standard.mdx @@ -1,9 +1,8 @@ --- description: Understanding token representation in Injective's multi-VM architecture +title: MultiVM Token Standard --- -# MultiVM Token Standard - ## What is MultiVM Token Standard (MTS)? MTS (MultiVM Token Standard) ensures that every token on Injective—whether deployed using Cosmos modules or via the Ethereum Virtual Machine (EVM)—has one canonical balance and identity. This unified approach prevents fragmentation and eliminates the need for bridging or wrapping tokens, thereby enabling seamless interoperability and unified liquidity for decentralized finance (DeFi) and dApp interactions. @@ -19,20 +18,20 @@ MTS (MultiVM Token Standard) ensures that every token on Injective—whether dep The system comprises two main components: -* [**Bank Precompile**](./bank-precompile.md): +* [**Bank Precompile**](./bank-precompile/): * Developed in Go, this precompile is embedded directly in the Injective EVM. * It provides a Solidity interface that proxies ERC20 operations—such as mint, burn, and transfer—to the bank module. -* [**ERC20 Module**](./erc20-module.md): +* [**ERC20 Module**](./erc20-module/): * This module maps native bank denoms (e.g., INJ, IBC tokens, Peggy assets) to an ERC20 contract within the EVM. * It deploys MTS-compliant ERC20 contracts that always reflect the canonical token balance as maintained by the bank module. -

Single Token Representation Architecture

+

Single Token Representation Architecture

### **Creating an** MTS**-Compliant Token** 1. [**Using Our Prebuilt Templates**](https://github.com/InjectiveLabs/solidity-contracts/tree/master/src): * Start with the provided Solidity templates, such as `BankERC20.sol`, `MintBurnBankERC20.sol`, or `FixedSupplyBankERC20.sol`. -2. [**Deploying the Contract**](./smart-contracts/README.md): +2. [**Deploying the Contract**](./smart-contracts/): * Deploy your MTS token contract on the Injective EVM network. * The contract automatically interacts with the Bank Precompile to update the canonical state. @@ -43,7 +42,7 @@ The system comprises two main components: Injective’s EVM is integrated directly into the Cosmos-based chain. * EVM smart contracts, when using MTS, perform operations that reflect immediately on native modules (such as the exchange, staking, and governance modules). -* [JSON-RPC endpoints](./network-information.md) provided within the Injective binary are compatible with Ethereum, ensuring smooth developer integration. +* [JSON-RPC endpoints](./network-information/) provided within the Injective binary are compatible with Ethereum, ensuring smooth developer integration. #### **Cross-Chain Operations** @@ -65,7 +64,7 @@ Injective’s EVM is integrated directly into the Cosmos-based chain. #### **Security** * The [bank module](../developers-native/core/bank/), as the single source of truth, underpins MTS’s security by ensuring that token balances are consistent and verifiable. -* The use of [precompiles](./precompiles.md) prevents common pitfalls like state desynchronization, ensuring that all operations—no matter where initiated—update the same canonical ledger. +* The use of [precompiles](./precompiles/) prevents common pitfalls like state desynchronization, ensuring that all operations—no matter where initiated—update the same canonical ledger. * Advanced security guidelines and best practices for smart contract development are provided in our security section and external resources. **ℹ️ Note:** diff --git a/.gitbook/developers-evm/network-information.mdx b/.gitbook/developers-evm/network-information.mdx index ad074a2..d17d73c 100644 --- a/.gitbook/developers-evm/network-information.mdx +++ b/.gitbook/developers-evm/network-information.mdx @@ -1,9 +1,8 @@ --- description: Essential information about the Injective EVM network +title: EVM Network Information --- -# EVM Network Information - ## Injective EVM Mainnet Details * Chain ID: `1776` @@ -16,7 +15,7 @@ description: Essential information about the Injective EVM network Note that the Injective Chain ID is natively `injective-1`. However, EVM uses a numeric chain ID of `1776`. While these are different, they map to the **same** network. -See [network information](../developers/network-information.md) for more details. +See [network information](../developers/network-information/) for more details. ### More Providers @@ -42,7 +41,7 @@ After the EVM Mainnet launch, there will be an initial permissioned period. Duri Note that the Injective Chain ID is natively `injective-888`. However, EVM uses a numeric chain ID of `1439`. While these are different, they map to the **same** network. -See [network information](../developers/network-information.md) for more details. +See [network information](../developers/network-information/) for more details. ### More Providers @@ -59,9 +58,9 @@ For more information about Injective EVM Testnet see the following pages: * Basics: * [Start Building on EVM](./) - * [Your first EVM smart contract](smart-contracts/) - * [Your first EVM dApp](dapps/) + * [Your first EVM smart contract](./smart-contracts/) + * [Your first EVM dApp](./dapps/) * Advanced: - * [EVM Equivalence](evm-equivalence.md) - * [MultiVM Token Standard](multivm-token-standard.md) - * [Precompiles](precompiles.md) + * [EVM Equivalence](./evm-equivalence/) + * [MultiVM Token Standard](./multivm-token-standard/) + * [Precompiles](./precompiles/) diff --git a/.gitbook/developers-evm/precompiles.mdx b/.gitbook/developers-evm/precompiles.mdx index 93d6bcf..de564af 100644 --- a/.gitbook/developers-evm/precompiles.mdx +++ b/.gitbook/developers-evm/precompiles.mdx @@ -1,4 +1,6 @@ -# Precompiles +--- +title: Precompiles +--- ### **What are Precompiles on Injective?** @@ -12,7 +14,7 @@ The Injective EVM doesn't operate in a silo. It's deeply integrated with Injecti Precompiles serve as the crucial **bridge** between the EVM world (where your Solidity contracts live) and these native Injective functionalities. Without precompiles, your EVM smart contracts would be isolated, unable to tap into the rich features and liquidity of the broader Injective ecosystem. -For example, our [MultiVM Token Standard (MTS)](./multivm-token-standard.md) model, which ensures unified token balances across native and EVM environments, is heavily reliant on the **Bank Precompile**. +For example, our [MultiVM Token Standard (MTS)](./multivm-token-standard/) model, which ensures unified token balances across native and EVM environments, is heavily reliant on the **Bank Precompile**. ### **Benefits for Developers** @@ -52,6 +54,6 @@ Jumpstart your development by cloning the [Injective Solidity Contracts Reposito | Name | Purpose | EVM address | | ---------------------------------- | ----------------------------- | ----------- | -| [Bank](bank-precompile.md) | Token Management | 0x64 | -| [Exchange](exchange-precompile.md) | On-chain Order Book | 0x65 | +| [Bank](./bank-precompile/) | Token Management | 0x64 | +| [Exchange](./exchange-precompile/) | On-chain Order Book | 0x65 | | Staking | Native staking token on-chain | 0x66 | diff --git a/.gitbook/developers-evm/smart-contracts/compile-foundry.mdx b/.gitbook/developers-evm/smart-contracts/compile-foundry.mdx index 5ebcf3e..4964b2c 100644 --- a/.gitbook/developers-evm/smart-contracts/compile-foundry.mdx +++ b/.gitbook/developers-evm/smart-contracts/compile-foundry.mdx @@ -1,4 +1,6 @@ -# Set up Foundry and compile a smart contract +--- +title: Set up Foundry and compile a smart contract +--- ## Prerequisites @@ -145,4 +147,4 @@ These artifacts are used in all later steps (test, deploy, verify, and interact) ## Next steps Now that you have set up a Foundry project and compiled a smart contract, you are ready to test that smart contract! -Check out the [test a smart contract using Foundry](./test-foundry.md) tutorial next. +Check out the [test a smart contract using Foundry](./test-foundry/) tutorial next. diff --git a/.gitbook/developers-evm/smart-contracts/compile-hardhat.mdx b/.gitbook/developers-evm/smart-contracts/compile-hardhat.mdx index 69fae45..fd74e4d 100644 --- a/.gitbook/developers-evm/smart-contracts/compile-hardhat.mdx +++ b/.gitbook/developers-evm/smart-contracts/compile-hardhat.mdx @@ -1,4 +1,6 @@ -# Set up Hardhat and compile a smart contract +--- +title: Set up Hardhat and compile a smart contract +--- ## Prerequisites @@ -139,4 +141,4 @@ These artifacts are used in all later steps (test, deploy, verify, and interact) ## Next steps Now that you have set up a Hardhat project and compiled a smart contract, you are ready to test that smart contract! -Check out the [test a smart contract using Hardhat](./test-hardhat.md) tutorial next. +Check out the [test a smart contract using Hardhat](./test-hardhat/) tutorial next. diff --git a/.gitbook/developers-evm/smart-contracts/deploy-foundry.mdx b/.gitbook/developers-evm/smart-contracts/deploy-foundry.mdx index 58344ad..2821ea6 100644 --- a/.gitbook/developers-evm/smart-contracts/deploy-foundry.mdx +++ b/.gitbook/developers-evm/smart-contracts/deploy-foundry.mdx @@ -1,12 +1,14 @@ -# Deploy a smart contract using Foundry +--- +title: Deploy a smart contract using Foundry +--- ## Prerequisites You should already have a Foundry project set up, and have compiled your smart contract successfully. -See the [set up Foundry and compile a smart contract](./compile-foundry.md) tutorial for how to do so. +See the [set up Foundry and compile a smart contract](./compile-foundry/) tutorial for how to do so. Optionally, but strongly recommended: You should also have tested your smart contract successfully. -See the [test a smart contract using Foundry](./test-foundry.md) tutorial for how to do so. +See the [test a smart contract using Foundry](./test-foundry/) tutorial for how to do so. ## Run the deployment @@ -25,7 +27,7 @@ forge create \ Note that we're using the `injTest` account saved to the keystore, -which was previously set up in [set up Foundry and compile a smart contract](./compile-foundry.md). +which was previously set up in [set up Foundry and compile a smart contract](./compile-foundry/). The output should look similar to: @@ -45,4 +47,4 @@ If you click on the "Contract" tab, you should see the EVM bytecode for that con ## Next steps Now that you have deployed your smart contract, you are ready to verify that smart contract! -Check out the [verify a smart contract using Foundry](./verify-foundry.md) tutorial next. +Check out the [verify a smart contract using Foundry](./verify-foundry/) tutorial next. diff --git a/.gitbook/developers-evm/smart-contracts/deploy-hardhat.mdx b/.gitbook/developers-evm/smart-contracts/deploy-hardhat.mdx index a779373..5111567 100644 --- a/.gitbook/developers-evm/smart-contracts/deploy-hardhat.mdx +++ b/.gitbook/developers-evm/smart-contracts/deploy-hardhat.mdx @@ -1,12 +1,14 @@ -# Deploy a smart contract using Hardhat +--- +title: Deploy a smart contract using Hardhat +--- ## Prerequisites You should already have a Hardhat project set up, and have compiled your smart contract successfully. -See the [set up Hardhat and compile a smart contract](./compile-hardhat.md) tutorial for how to do so. +See the [set up Hardhat and compile a smart contract](./compile-hardhat/) tutorial for how to do so. Optionally, but strongly recommended: You should also have tested your smart contract successfully. -See the [test a smart contract using Hardhat](./test-hardhat.md) tutorial for how to do so. +See the [test a smart contract using Hardhat](./test-hardhat/) tutorial for how to do so. ## Edit the deployment script @@ -53,4 +55,4 @@ If you click on the "Contract" tab, you should see the EVM bytecode for that con ## Next steps Now that you have deployed your smart contract, you are ready to verify that smart contract! -Check out the [verify a smart contract using Hardhat](./verify-hardhat.md) tutorial next. +Check out the [verify a smart contract using Hardhat](./verify-hardhat/) tutorial next. diff --git a/.gitbook/developers-evm/smart-contracts.mdx b/.gitbook/developers-evm/smart-contracts/index.mdx similarity index 67% rename from .gitbook/developers-evm/smart-contracts.mdx rename to .gitbook/developers-evm/smart-contracts/index.mdx index e5167e0..66bf2b3 100644 --- a/.gitbook/developers-evm/smart-contracts.mdx +++ b/.gitbook/developers-evm/smart-contracts/index.mdx @@ -1,4 +1,6 @@ -# Your First EVM Smart Contract +--- +title: Your First EVM Smart Contract +--- Smart contracts are code that runs on a blockchain. You can compile Solidity smart contracts, @@ -10,24 +12,24 @@ These guides show you how to do so using Hardhat and Foundry. This guide will walk you through building an EVM Smart Contract on Injective Testnet using [Hardhat](https://hardhat.org/). -* [Set up Hardhat and compile a smart contract](./compile-hardhat.md) -* [Test a smart contract using Hardhat](./test-hardhat.md) -* [Deploy a smart contract using Hardhat](./deploy-hardhat.md) -* [Verify a smart contract using Hardhat](./verify-hardhat.md) -* [Interact with a smart contract using Hardhat](./interact-hardhat.md) +* [Set up Hardhat and compile a smart contract](./compile-hardhat/) +* [Test a smart contract using Hardhat](./test-hardhat/) +* [Deploy a smart contract using Hardhat](./deploy-hardhat/) +* [Verify a smart contract using Hardhat](./verify-hardhat/) +* [Interact with a smart contract using Hardhat](./interact-hardhat/) ## Foundry This guide will walk you through building an EVM Smart Contract on Injective Testnet using [Foundry](https://getfoundry.sh/). -* [Set up Foundry and compile a smart contract](./compile-foundry.md) -* [Test a smart contract using Foundry](./test-foundry.md) -* [Deploy a smart contract using Foundry](./deploy-foundry.md) -* [Verify a smart contract using Foundry](./verify-foundry.md) -* [Interact with a smart contract using Foundry](./interact-foundry.md) +* [Set up Foundry and compile a smart contract](./compile-foundry/) +* [Test a smart contract using Foundry](./test-foundry/) +* [Deploy a smart contract using Foundry](./deploy-foundry/) +* [Verify a smart contract using Foundry](./verify-foundry/) +* [Interact with a smart contract using Foundry](./interact-foundry/) ## Next steps Smart contracts do not provide a user experience for non-technical users. To cater to them, you will need to build a decentralised application. -To do so, check out the [your first dApp](../dapps/README.md) guides! +To do so, check out the [your first dApp](../dapps/) guides! diff --git a/.gitbook/developers-evm/smart-contracts/interact-foundry.mdx b/.gitbook/developers-evm/smart-contracts/interact-foundry.mdx index 2299273..92f8f69 100644 --- a/.gitbook/developers-evm/smart-contracts/interact-foundry.mdx +++ b/.gitbook/developers-evm/smart-contracts/interact-foundry.mdx @@ -1,12 +1,14 @@ -# Interact with a smart contract using Foundry +--- +title: Interact with a smart contract using Foundry +--- ## Prerequisites You should already have a Foundry project set up, and have deployed your smart contract successfully. -See the [deploy a smart contract using Foundry](./deploy-foundry.md) tutorial for how to do so. +See the [deploy a smart contract using Foundry](./deploy-foundry/) tutorial for how to do so. Optionally, but strongly recommended: You should also have successfully verified your smart contract. -See the [verify a smart contract using Foundry](./verify-foundry.md) tutorial for how to do so. +See the [verify a smart contract using Foundry](./verify-foundry/) tutorial for how to do so. ## Invoke function - query @@ -131,4 +133,4 @@ Congratulations, you have completed this entire guide for developing EVM smart c Smart contracts do not provide a user experience for non-technical users. To cater to them, you will need to build a decentralised application. -To do so, check out the [your first dApp](../dapps/README.md) guides! +To do so, check out the [your first dApp](../dapps/) guides! diff --git a/.gitbook/developers-evm/smart-contracts/interact-hardhat.mdx b/.gitbook/developers-evm/smart-contracts/interact-hardhat.mdx index 9e24caa..b040086 100644 --- a/.gitbook/developers-evm/smart-contracts/interact-hardhat.mdx +++ b/.gitbook/developers-evm/smart-contracts/interact-hardhat.mdx @@ -1,12 +1,14 @@ -# Interact with a smart contract using Hardhat +--- +title: Interact with a smart contract using Hardhat +--- ## Prerequisites You should already have a Hardhat project set up, and have deployed your smart contract successfully. -See the [deploy a smart contract using Hardhat](./deploy-hardhat.md) tutorial for how to do so. +See the [deploy a smart contract using Hardhat](./deploy-hardhat/) tutorial for how to do so. Optionally, but strongly recommended: You should also have successfully verified your smart contract. -See the [verify a smart contract using Hardhat](./verify-hardhat.md) tutorial for how to do so. +See the [verify a smart contract using Hardhat](./verify-hardhat/) tutorial for how to do so. ## Start the Hardhat console @@ -113,4 +115,4 @@ Congratulations, you have completed this entire guide for developing EVM smart c Smart contracts do not provide a user experience for non-technical users. To cater to them, you will need to build a decentralised application. -To do so, check out the [your first dApp](../dapps/README.md) guides! +To do so, check out the [your first dApp](../dapps/) guides! diff --git a/.gitbook/developers-evm/smart-contracts/test-foundry.mdx b/.gitbook/developers-evm/smart-contracts/test-foundry.mdx index 961dade..8500fb1 100644 --- a/.gitbook/developers-evm/smart-contracts/test-foundry.mdx +++ b/.gitbook/developers-evm/smart-contracts/test-foundry.mdx @@ -1,9 +1,11 @@ -# Test a smart contract using Foundry +--- +title: Test a smart contract using Foundry +--- ## Prerequisites You should already have a Foundry project set up, and have compiled your smart contract successfully. -See the [set up Foundry and compile a smart contract](./compile-foundry.md) tutorial for how to do so. +See the [set up Foundry and compile a smart contract](./compile-foundry/) tutorial for how to do so. ## Edit the test specifications @@ -79,5 +81,4 @@ Ran 1 test suite in 171.04ms (5.35ms CPU time): 3 tests passed, 0 failed, 0 skip ## Next steps Now that you have tested your smart contract, you are ready to deploy that smart contract! -Check out the [deploy a smart contract using Foundry](./deploy-foundry.md) tutorial next. - +Check out the [deploy a smart contract using Foundry](./deploy-foundry/) tutorial next. diff --git a/.gitbook/developers-evm/smart-contracts/test-hardhat.mdx b/.gitbook/developers-evm/smart-contracts/test-hardhat.mdx index 860c5b3..1baa1f3 100644 --- a/.gitbook/developers-evm/smart-contracts/test-hardhat.mdx +++ b/.gitbook/developers-evm/smart-contracts/test-hardhat.mdx @@ -1,9 +1,11 @@ -# Test a smart contract using Hardhat +--- +title: Test a smart contract using Hardhat +--- ## Prerequisites You should already have a Hardhat project set up, and have compiled your smart contract successfully. -See the [set up Hardhat and compile a smart contract](./compile-hardhat.md) tutorial for how to do so. +See the [set up Hardhat and compile a smart contract](./compile-hardhat/) tutorial for how to do so. ## Edit the test specifications @@ -84,4 +86,4 @@ This is followed by a table which includes additional reporting on gas, which is ## Next steps Now that you have tested your smart contract, you are ready to deploy that smart contract! -Check out the [deploy a smart contract using Hardhat](./deploy-hardhat.md) tutorial next. +Check out the [deploy a smart contract using Hardhat](./deploy-hardhat/) tutorial next. diff --git a/.gitbook/developers-evm/smart-contracts/verify-foundry.mdx b/.gitbook/developers-evm/smart-contracts/verify-foundry.mdx index d90c0f5..f87f4ff 100644 --- a/.gitbook/developers-evm/smart-contracts/verify-foundry.mdx +++ b/.gitbook/developers-evm/smart-contracts/verify-foundry.mdx @@ -1,9 +1,11 @@ -# Verify a smart contract using Foundry +--- +title: Verify a smart contract using Foundry +--- ## Prerequisites You should already have a Foundry project set up, and have deployed your smart contract successfully. -See the [deploy a smart contract using Foundry](./deploy-foundry.md) tutorial for how to do so. +See the [deploy a smart contract using Foundry](./deploy-foundry/) tutorial for how to do so. ## What is smart contract verification? @@ -75,4 +77,4 @@ but now you can interact with every smart contract function directly from the bl ## Next steps Now that you have deployed and verified your smart contract, you are ready to interact with that smart contract! -Check out the [interact with a smart contract using Foundry](./interact-foundry.md) tutorial next. +Check out the [interact with a smart contract using Foundry](./interact-foundry/) tutorial next. diff --git a/.gitbook/developers-evm/smart-contracts/verify-hardhat.mdx b/.gitbook/developers-evm/smart-contracts/verify-hardhat.mdx index 877de6c..bbe8741 100644 --- a/.gitbook/developers-evm/smart-contracts/verify-hardhat.mdx +++ b/.gitbook/developers-evm/smart-contracts/verify-hardhat.mdx @@ -1,9 +1,11 @@ -# Verify a smart contract using Hardhat +--- +title: Verify a smart contract using Hardhat +--- ## Prerequisites You should already have a Hardhat project set up, and have deployed your smart contract successfully. -See the [deploy a smart contract using Hardhat](./deploy-hardhat.md) tutorial for how to do so. +See the [deploy a smart contract using Hardhat](./deploy-hardhat/) tutorial for how to do so. ## What is smart contract verification? @@ -95,4 +97,4 @@ but now you can interact with every smart contract function directly from the bl ## Next steps Now that you have deployed and verified your smart contract, you are ready to interact with that smart contract! -Check out the [interact with a smart contract using Hardhat](./interact-hardhat.md) tutorial next. +Check out the [interact with a smart contract using Hardhat](./interact-hardhat/) tutorial next. diff --git a/.gitbook/developers-native/bridges.mdx b/.gitbook/developers-native/bridges.mdx index 174fa03..3a1f514 100644 --- a/.gitbook/developers-native/bridges.mdx +++ b/.gitbook/developers-native/bridges.mdx @@ -1,4 +1,6 @@ -# Bridge +--- +title: Bridge +--- Injective is a blockchain built specifically to support financial applications. A key strength of Injective is its ability to perform seamless cross-chain transactions with the majority of popular blockchains. @@ -6,9 +8,9 @@ Injective is a blockchain built specifically to support financial applications. | Topic | Description | | -------------------------------------- | ----------------------------------------- | -| [Peggy (Ethereum Bridge)](ethereum.md) | Bridging to/from Injective ↔ Ethereum | +| [Peggy (Ethereum Bridge)](./bridges/ethereum/) | Bridging to/from Injective ↔ Ethereum | {/* -| [IBC Bridge](ibc.md) | Bridging to/from Injective using IBC | -| [Wormhole Bridge](wormhole.md) | Bridging to/from Injective using Wormhole | +| [IBC Bridge](./bridges/ibc/) | Bridging to/from Injective using IBC | +| [Wormhole Bridge](./bridges/wormhole/) | Bridging to/from Injective using Wormhole | */} diff --git a/.gitbook/developers-native/bridges/ethereum.mdx b/.gitbook/developers-native/bridges/ethereum.mdx index c9b4db8..22d8b12 100644 --- a/.gitbook/developers-native/bridges/ethereum.mdx +++ b/.gitbook/developers-native/bridges/ethereum.mdx @@ -1,4 +1,6 @@ -# Ethereum Bridge +--- +title: Ethereum Bridge +--- The Injective Ethereum bridge enables the Injective Chain to support a trustless, on-chain bidirectional token bridge. In this system, holders of ERC-20 tokens on Ethereum can instantaneously convert their ERC-20 tokens to Cosmos-native coins on the Injective Chain and vice-versa. diff --git a/.gitbook/developers-native/core.mdx b/.gitbook/developers-native/core.mdx index dc0a11b..7c18c9f 100644 --- a/.gitbook/developers-native/core.mdx +++ b/.gitbook/developers-native/core.mdx @@ -1,3 +1,5 @@ -# Core +--- +title: Core +--- ## Core Modules diff --git a/.gitbook/developers-native/core/auth.mdx b/.gitbook/developers-native/core/auth/index.md similarity index 92% rename from .gitbook/developers-native/core/auth.mdx rename to .gitbook/developers-native/core/auth/index.md index 9144abc..bd9f18a 100644 --- a/.gitbook/developers-native/core/auth.mdx +++ b/.gitbook/developers-native/core/auth/index.md @@ -2,33 +2,33 @@ sidebar_position: 1 --- -# Auth +# `x/auth` ## Abstract This document specifies the auth module of the Cosmos SDK. -The auth module is responsible for specifying the base transaction and account types\ -for an application, since the SDK itself is agnostic to these particulars. It contains\ -the middlewares, where all basic transaction validity checks (signatures, nonces, auxiliary fields)\ +The auth module is responsible for specifying the base transaction and account types +for an application, since the SDK itself is agnostic to these particulars. It contains +the middlewares, where all basic transaction validity checks (signatures, nonces, auxiliary fields) are performed, and exposes the account keeper, which allows other modules to read, write, and modify accounts. This module is used in the Cosmos Hub. ## Contents -* [Concepts](./#concepts) - * [Gas & Fees](./#gas--fees) -* [State](./#state) - * [Accounts](./#accounts) -* [AnteHandlers](./#antehandlers) -* [Keepers](./#keepers) - * [Account Keeper](./#account-keeper) -* [Parameters](./#parameters) -* [Client](./#client) - * [CLI](./#cli) - * [gRPC](./#grpc) - * [REST](./#rest) +* [Concepts](#concepts) + * [Gas & Fees](#gas--fees) +* [State](#state) + * [Accounts](#accounts) +* [AnteHandlers](#antehandlers) +* [Keepers](#keepers) + * [Account Keeper](#account-keeper) +* [Parameters](#parameters) +* [Client](#client) + * [CLI](#cli) + * [gRPC](#grpc) + * [REST](#rest) ## Concepts @@ -43,52 +43,53 @@ The differences are: Fees serve two purposes for an operator of the network. -Fees limit the growth of the state stored by every full node and allow for\ -general purpose censorship of transactions of little economic value. Fees\ -are best suited as an anti-spam mechanism where validators are disinterested in\ +Fees limit the growth of the state stored by every full node and allow for +general purpose censorship of transactions of little economic value. Fees +are best suited as an anti-spam mechanism where validators are disinterested in the use of the network and identities of users. -Fees are determined by the gas limits and gas prices transactions provide, where`fees = ceil(gasLimit * gasPrices)`. Txs incur gas costs for all state reads/writes,\ -signature verification, as well as costs proportional to the tx size. Operators\ -should set minimum gas prices when starting their nodes. They must set the unit\ +Fees are determined by the gas limits and gas prices transactions provide, where +`fees = ceil(gasLimit * gasPrices)`. Txs incur gas costs for all state reads/writes, +signature verification, as well as costs proportional to the tx size. Operators +should set minimum gas prices when starting their nodes. They must set the unit costs of gas in each token denomination they wish to support: `simd start ... --minimum-gas-prices=0.00001stake;0.05photinos` -When adding transactions to mempool or gossipping transactions, validators check\ -if the transaction's gas prices, which are determined by the provided fees, meet\ -any of the validator's minimum gas prices. In other words, a transaction must\ -provide a fee of at least one denomination that matches a validator's minimum\ +When adding transactions to mempool or gossipping transactions, validators check +if the transaction's gas prices, which are determined by the provided fees, meet +any of the validator's minimum gas prices. In other words, a transaction must +provide a fee of at least one denomination that matches a validator's minimum gas price. -CometBFT does not currently provide fee based mempool prioritization, and fee\ -based mempool filtering is local to node and not part of consensus. But with\ +CometBFT does not currently provide fee based mempool prioritization, and fee +based mempool filtering is local to node and not part of consensus. But with minimum gas prices set, such a mechanism could be implemented by node operators. -Because the market value for tokens will fluctuate, validators are expected to\ -dynamically adjust their minimum gas prices to a level that would encourage the\ -use of the network. +Because the market value for tokens will fluctuate, validators are expected to +dynamically adjust their minimum gas prices to a level that would encourage the +use of the network. ## State ### Accounts -Accounts contain authentication information for a uniquely identified external user of an SDK blockchain,\ -including public key, address, and account number / sequence number for replay protection. For efficiency,\ -since account balances must also be fetched to pay fees, account structs also store the balance of a user\ +Accounts contain authentication information for a uniquely identified external user of an SDK blockchain, +including public key, address, and account number / sequence number for replay protection. For efficiency, +since account balances must also be fetched to pay fees, account structs also store the balance of a user as `sdk.Coins`. -Accounts are exposed externally as an interface, and stored internally as\ -either a base account or vesting account. Module clients wishing to add more\ +Accounts are exposed externally as an interface, and stored internally as +either a base account or vesting account. Module clients wishing to add more account types may do so. -* `0x01 | Address → ProtocolBuffer(account)` +* `0x01 | Address -> ProtocolBuffer(account)` #### Account Interface -The account interface exposes methods to read and write standard account information.\ -Note that all of these methods operate on an account struct conforming to the\ -interface - in order to write the account to the store, the account keeper will\ +The account interface exposes methods to read and write standard account information. +Note that all of these methods operate on an account struct conforming to the +interface - in order to write the account to the store, the account keeper will need to be used. ```go @@ -118,9 +119,9 @@ type AccountI interface { } ``` -**Base Account** +##### Base Account -A base account is the simplest and most common account type, which just stores all requisite\ +A base account is the simplest and most common account type, which just stores all requisite fields directly in a struct. ```protobuf @@ -141,7 +142,7 @@ See [Vesting](https://docs.cosmos.network/main/modules/auth/vesting/). ## AnteHandlers -The `x/auth` module presently has no transaction handlers of its own, but does expose the special `AnteHandler`, used for performing basic validity checks on a transaction, such that it could be thrown out of the mempool.\ +The `x/auth` module presently has no transaction handlers of its own, but does expose the special `AnteHandler`, used for performing basic validity checks on a transaction, such that it could be thrown out of the mempool. The `AnteHandler` can be seen as a set of decorators that check transactions within the current context, per [ADR 010](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-010-modular-antehandler.md). Note that the `AnteHandler` is called on both `CheckTx` and `DeliverTx`, as CometBFT proposers presently have the ability to include in their proposed block transactions which fail `CheckTx`. @@ -151,17 +152,29 @@ Note that the `AnteHandler` is called on both `CheckTx` and `DeliverTx`, as Come The auth module provides `AnteDecorator`s that are recursively chained together into a single `AnteHandler` in the following order: * `SetUpContextDecorator`: Sets the `GasMeter` in the `Context` and wraps the next `AnteHandler` with a defer clause to recover from any downstream `OutOfGas` panics in the `AnteHandler` chain to return an error with information on gas provided and gas used. + * `RejectExtensionOptionsDecorator`: Rejects all extension options which can optionally be included in protobuf transactions. + * `MempoolFeeDecorator`: Checks if the `tx` fee is above local mempool `minFee` parameter during `CheckTx`. + * `ValidateBasicDecorator`: Calls `tx.ValidateBasic` and returns any non-nil error. + * `TxTimeoutHeightDecorator`: Check for a `tx` height timeout. + * `ValidateMemoDecorator`: Validates `tx` memo with application parameters and returns any non-nil error. + * `ConsumeGasTxSizeDecorator`: Consumes gas proportional to the `tx` size based on application parameters. + * `DeductFeeDecorator`: Deducts the `FeeAmount` from first signer of the `tx`. If the `x/feegrant` module is enabled and a fee granter is set, it deducts fees from the fee granter account. + * `SetPubKeyDecorator`: Sets the pubkey from a `tx`'s signers that does not already have its corresponding pubkey saved in the state machine and in the current context. + * `ValidateSigCountDecorator`: Validates the number of signatures in `tx` based on app-parameters. + * `SigGasConsumeDecorator`: Consumes parameter-defined amount of gas for each signature. This requires pubkeys to be set in context for all signers as part of `SetPubKeyDecorator`. + * `SigVerificationDecorator`: Verifies all signatures are valid. This requires pubkeys to be set in context for all signers as part of `SetPubKeyDecorator`. + * `IncrementSequenceDecorator`: Increments the account sequence for each signer to prevent replay attacks. ## Keepers @@ -170,7 +183,7 @@ The auth module only exposes one keeper, the account keeper, which can be used t ### Account Keeper -Presently only one fully-permissioned account keeper is exposed, which has the ability to both read and write\ +Presently only one fully-permissioned account keeper is exposed, which has the ability to both read and write all fields of all accounts, and to iterate over all stored accounts. ```go @@ -212,13 +225,13 @@ type AccountKeeperI interface { The auth module contains the following parameters: -| Key | Type | Example | -| ---------------------- | ------ | ------- | -| MaxMemoCharacters | uint64 | 256 | -| TxSigLimit | uint64 | 7 | -| TxSizeCostPerByte | uint64 | 10 | -| SigVerifyCostED25519 | uint64 | 590 | -| SigVerifyCostSecp256k1 | uint64 | 1000 | +| Key | Type | Example | +| ---------------------- | --------------- | ------- | +| MaxMemoCharacters | uint64 | 256 | +| TxSigLimit | uint64 | 7 | +| TxSizeCostPerByte | uint64 | 10 | +| SigVerifyCostED25519 | uint64 | 590 | +| SigVerifyCostSecp256k1 | uint64 | 1000 | ## Client @@ -407,7 +420,7 @@ More information about the `sign` command can be found running `simd tx sign --h #### `sign-batch` -The `sign-batch` command allows users to sign multiples offline generated transactions.\ +The `sign-batch` command allows users to sign multiples offline generated transactions. The transactions can be in one file, with one tx per line, or in multiple files. ```bash @@ -416,7 +429,7 @@ simd tx sign txs.json --from $ALICE > tx.signed.json or -```bash +```bash simd tx sign tx1.json tx2.json tx3.json --from $ALICE > tx.signed.json ``` @@ -434,7 +447,7 @@ simd tx multisign transaction.json k1k2k3 k1sig.json k2sig.json k3sig.json Where `k1k2k3` is the multisig account address, `k1sig.json` is the signature of the first signer, `k2sig.json` is the signature of the second signer, and `k3sig.json` is the signature of the third signer. -**Nested multisig transactions** +##### Nested multisig transactions To allow transactions to be signed by nested multisigs, meaning that a participant of a multisig account can be another multisig account, the `--skip-signature-verification` flag must be used. @@ -454,7 +467,7 @@ More information about the `multi-sign` command can be found running `simd tx mu #### `multisign-batch` -The `multisign-batch` works the same way as `sign-batch`, but for multisig accounts.\ +The `multisign-batch` works the same way as `sign-batch`, but for multisig accounts. With the difference that the `multisign-batch` command requires all transactions to be in one file, and the `--append` flag does not exist. More information about the `multisign-batch` command can be found running `simd tx multisign-batch --help`. @@ -484,6 +497,7 @@ simd tx broadcast tx.signed.json More information about the `broadcast` command can be found running `simd tx broadcast --help`. + ### gRPC A user can query the `auth` module using gRPC endpoints. diff --git a/.gitbook/developers-native/core/authz.mdx b/.gitbook/developers-native/core/authz/index.md similarity index 86% rename from .gitbook/developers-native/core/authz.mdx rename to .gitbook/developers-native/core/authz/index.md index 6d92f6b..b924eaf 100644 --- a/.gitbook/developers-native/core/authz.mdx +++ b/.gitbook/developers-native/core/authz/index.md @@ -2,45 +2,45 @@ sidebar_position: 1 --- -# AuthZ +# `x/authz` ## Abstract -`x/authz` is an implementation of a Cosmos SDK module, per [ADR 30](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-030-authz-module.md), that allows\ +`x/authz` is an implementation of a Cosmos SDK module, per [ADR 30](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-030-authz-module.md), that allows granting arbitrary privileges from one account (the granter) to another account (the grantee). Authorizations must be granted for a particular Msg service method one by one using an implementation of the `Authorization` interface. ## Contents -* [Concepts](./#concepts) - * [Authorization and Grant](./#authorization-and-grant) - * [Built-in Authorizations](./#built-in-authorizations) - * [Gas](./#gas) -* [State](./#state) - * [Grant](./#grant) - * [GrantQueue](./#grantqueue) -* [Messages](./#messages) - * [MsgGrant](./#msggrant) - * [MsgRevoke](./#msgrevoke) - * [MsgExec](./#msgexec) -* [Events](./#events) -* [Client](./#client) - * [CLI](./#cli) - * [gRPC](./#grpc) - * [REST](./#rest) +* [Concepts](#concepts) + * [Authorization and Grant](#authorization-and-grant) + * [Built-in Authorizations](#built-in-authorizations) + * [Gas](#gas) +* [State](#state) + * [Grant](#grant) + * [GrantQueue](#grantqueue) +* [Messages](#messages) + * [MsgGrant](#msggrant) + * [MsgRevoke](#msgrevoke) + * [MsgExec](#msgexec) +* [Events](#events) +* [Client](#client) + * [CLI](#cli) + * [gRPC](#grpc) + * [REST](#rest) ## Concepts ### Authorization and Grant -The `x/authz` module defines interfaces and messages grant authorizations to perform actions\ +The `x/authz` module defines interfaces and messages grant authorizations to perform actions on behalf of one account to other accounts. The design is defined in the [ADR 030](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-030-authz-module.md). -A _grant_ is an allowance to execute a Msg by the grantee on behalf of the granter.\ +A *grant* is an allowance to execute a Msg by the grantee on behalf of the granter. Authorization is an interface that must be implemented by a concrete authorization logic to validate and execute grants. Authorizations are extensible and can be defined for any Msg service method even outside of the module where the Msg method is defined. See the `SendAuthorization` example in the next section for more details. **Note:** The authz module is different from the [auth (authentication)](../auth/) module that is responsible for specifying the base transaction and account types. -```go +```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/authz/authorizations.go#L11-L25 ``` @@ -52,11 +52,11 @@ The Cosmos SDK `x/authz` module comes with following authorization types: `GenericAuthorization` implements the `Authorization` interface that gives unrestricted permission to execute the provided Msg on behalf of granter's account. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/authz/v1beta1/authz.proto#L14-L22 ``` -```go +```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/authz/generic_authorization.go#L16-L29 ``` @@ -69,11 +69,11 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/authz/generic_authorizat * It takes a (positive) `SpendLimit` that specifies the maximum amount of tokens the grantee can spend. The `SpendLimit` is updated as the tokens are spent. * It takes an (optional) `AllowList` that specifies to which addresses a grantee can send token. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/bank/v1beta1/authz.proto#L11-L30 ``` -```go +```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/bank/types/send_authorization.go#L29-L62 ``` @@ -84,11 +84,11 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/bank/types/send_authoriz `StakeAuthorization` implements the `Authorization` interface for messages in the [staking module](https://docs.cosmos.network/v0.50/build/modules/staking). It takes an `AuthorizationType` to specify whether you want to authorise delegating, undelegating or redelegating (i.e. these have to be authorised separately). It also takes an optional `MaxTokens` that keeps track of a limit to the amount of tokens that can be delegated/undelegated/redelegated. If left empty, the amount is unlimited. Additionally, this Msg takes an `AllowList` or a `DenyList`, which allows you to select which validators you allow or deny grantees to stake with. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/authz.proto#L11-L35 ``` -```go +```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/staking/types/authz.go#L15-L35 ``` @@ -104,11 +104,11 @@ Since the state maintaining a list for granter, grantee pair with same expiratio Grants are identified by combining granter address (the address bytes of the granter), grantee address (the address bytes of the grantee) and Authorization type (its type URL). Hence we only allow one grant for the (granter, grantee, Authorization) triple. -* Grant: `0x01 | granter_address_len (1 byte) | granter_address_bytes | grantee_address_len (1 byte) | grantee_address_bytes | msgType_bytes → ProtocolBuffer(AuthorizationGrant)` +* Grant: `0x01 | granter_address_len (1 byte) | granter_address_bytes | grantee_address_len (1 byte) | grantee_address_bytes | msgType_bytes -> ProtocolBuffer(AuthorizationGrant)` The grant object encapsulates an `Authorization` type and an expiration timestamp: -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/authz/v1beta1/authz.proto#L24-L32 ``` @@ -118,15 +118,15 @@ We are maintaining a queue for authz pruning. Whenever a grant is created, an it In `EndBlock` (which runs for every block) we continuously check and prune the expired grants by forming a prefix key with current blocktime that passed the stored expiration in `GrantQueue`, we iterate through all the matched records from `GrantQueue` and delete them from the `GrantQueue` & `Grant`s store. -```go +```go reference https://github.com/cosmos/cosmos-sdk/blob/5f4ddc6f80f9707320eec42182184207fff3833a/x/authz/keeper/keeper.go#L378-L403 ``` -* GrantQueue: `0x02 | expiration_bytes | granter_address_len (1 byte) | granter_address_bytes | grantee_address_len (1 byte) | grantee_address_bytes → ProtocalBuffer(GrantQueueItem)` +* GrantQueue: `0x02 | expiration_bytes | granter_address_len (1 byte) | granter_address_bytes | grantee_address_len (1 byte) | grantee_address_bytes -> ProtocalBuffer(GrantQueueItem)` The `expiration_bytes` are the expiration date in UTC with the format `"2006-01-02T15:04:05.000000000"`. -```go +```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/authz/keeper/keys.go#L77-L93 ``` @@ -138,10 +138,10 @@ In this section we describe the processing of messages for the authz module. ### MsgGrant -An authorization grant is created using the `MsgGrant` message.\ +An authorization grant is created using the `MsgGrant` message. If there is already a grant for the `(granter, grantee, Authorization)` triple, then the new grant overwrites the previous one. To update or extend an existing grant, a new grant with the same `(granter, grantee, Authorization)` triple should be created. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/authz/v1beta1/tx.proto#L35-L45 ``` @@ -156,7 +156,7 @@ The message handling should fail if: A grant can be removed with the `MsgRevoke` message. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/authz/v1beta1/tx.proto#L69-L78 ``` @@ -171,7 +171,7 @@ NOTE: The `MsgExec` message removes a grant if the grant has expired. When a grantee wants to execute a transaction on behalf of a granter, they must send `MsgExec`. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/authz/v1beta1/tx.proto#L52-L63 ``` @@ -199,7 +199,7 @@ The `query` commands allow users to query `authz` state. simd query authz --help ``` -**grants** +##### grants The `grants` command allows users to query grants for a granter-grantee pair. If the message type URL is set, it selects grants only for that message type. @@ -234,7 +234,7 @@ The `tx` commands allow users to interact with the `authz` module. simd tx authz --help ``` -**exec** +##### exec The `exec` command allows a grantee to execute a transaction on behalf of granter. @@ -248,34 +248,29 @@ Example: simd tx authz exec tx.json --from=cosmos1.. ``` -**grant** +##### grant The `grant` command allows a granter to grant an authorization to a grantee. ```bash simd tx authz grant --from [flags] ``` - -* The `send` authorization\_type refers to the built-in `SendAuthorization` type. The custom flags available are `spend-limit` (required) and `allow-list` (optional) , documented [here](./#SendAuthorization) +- The `send` authorization_type refers to the built-in `SendAuthorization` type. The custom flags available are `spend-limit` (required) and `allow-list` (optional) , documented [here](#SendAuthorization) Example: ```bash simd tx authz grant cosmos1.. send --spend-limit=100stake --allow-list=cosmos1...,cosmos2... --from=cosmos1.. ``` - -* The `generic` authorization\_type refers to the built-in `GenericAuthorization` type. The custom flag available is `msg-type` ( required) documented [here](./#GenericAuthorization). +- The `generic` authorization_type refers to the built-in `GenericAuthorization` type. The custom flag available is `msg-type` ( required) documented [here](#GenericAuthorization). > Note: `msg-type` is any valid Cosmos SDK `Msg` type url. Example: - ```bash simd tx authz grant cosmos1.. generic --msg-type=/cosmos.bank.v1beta1.MsgSend --from=cosmos1.. ``` - -* The `delegate`,`unbond`,`redelegate` authorization\_types refer to the built-in `StakeAuthorization` type. The custom flags available are `spend-limit` (optional), `allowed-validators` (optional) and `deny-validators` (optional) documented [here](./#StakeAuthorization). - +- The `delegate`,`unbond`,`redelegate` authorization_types refer to the built-in `StakeAuthorization` type. The custom flags available are `spend-limit` (optional), `allowed-validators` (optional) and `deny-validators` (optional) documented [here](#StakeAuthorization). > Note: `allowed-validators` and `deny-validators` cannot both be empty. `spend-limit` represents the `MaxTokens` Example: @@ -284,7 +279,7 @@ Example: simd tx authz grant cosmos1.. delegate --spend-limit=100stake --allowed-validators=cosmos...,cosmos... --deny-validators=cosmos... --from=cosmos1.. ``` -**revoke** +##### revoke The `revoke` command allows a granter to revoke an authorization from a grantee. diff --git a/.gitbook/developers-native/core/bank.mdx b/.gitbook/developers-native/core/bank/index.md similarity index 93% rename from .gitbook/developers-native/core/bank.mdx rename to .gitbook/developers-native/core/bank/index.md index 692ec38..885a9f1 100644 --- a/.gitbook/developers-native/core/bank.mdx +++ b/.gitbook/developers-native/core/bank/index.md @@ -2,44 +2,44 @@ sidebar_position: 1 --- -# Bank +# `x/bank` ## Abstract This document specifies the bank module of the Cosmos SDK. -The bank module is responsible for handling multi-asset coin transfers between\ -accounts and tracking special-case pseudo-transfers which must work differently\ -with particular kinds of accounts (notably delegating/undelegating for vesting\ -accounts). It exposes several interfaces with varying capabilities for secure\ +The bank module is responsible for handling multi-asset coin transfers between +accounts and tracking special-case pseudo-transfers which must work differently +with particular kinds of accounts (notably delegating/undelegating for vesting +accounts). It exposes several interfaces with varying capabilities for secure interaction with other modules which must alter user balances. -In addition, the bank module tracks and provides query support for the total\ +In addition, the bank module tracks and provides query support for the total supply of all assets used in the application. This module is used in the Cosmos Hub. ## Contents -* [Supply](./#supply) - * [Total Supply](./#total-supply) -* [Module Accounts](./#module-accounts) - * [Permissions](./#permissions) -* [State](./#state) -* [Params](./#params) -* [Keepers](./#keepers) -* [Messages](./#messages) -* [Events](./#events) - * [Message Events](./#message-events) - * [Keeper Events](./#keeper-events) -* [Parameters](./#parameters) - * [SendEnabled](./#sendenabled) - * [DefaultSendEnabled](./#defaultsendenabled) -* [Client](./#client) - * [CLI](./#cli) - * [Query](./#query) - * [Transactions](./#transactions) -* [gRPC](./#grpc) +* [Supply](#supply) + * [Total Supply](#total-supply) +* [Module Accounts](#module-accounts) + * [Permissions](#permissions) +* [State](#state) +* [Params](#params) +* [Keepers](#keepers) +* [Messages](#messages) +* [Events](#events) + * [Message Events](#message-events) + * [Keeper Events](#keeper-events) +* [Parameters](#parameters) + * [SendEnabled](#sendenabled) + * [DefaultSendEnabled](#defaultsendenabled) +* [Client](#client) + * [CLI](#cli) + * [Query](#query) + * [Transactions](#transactions) +* [gRPC](#grpc) ## Supply @@ -51,20 +51,21 @@ The `supply` functionality: ### Total Supply -The total `Supply` of the network is equal to the sum of all coins from the\ -account. The total supply is updated every time a `Coin` is minted (eg: as part\ -of the inflation mechanism) or burned (eg: due to slashing or if a governance\ +The total `Supply` of the network is equal to the sum of all coins from the +account. The total supply is updated every time a `Coin` is minted (eg: as part +of the inflation mechanism) or burned (eg: due to slashing or if a governance proposal is vetoed). ## Module Accounts -The supply functionality introduces a new type of `auth.Account` which can be used by\ -modules to allocate tokens and in special cases mint or burn tokens. At a base\ -level these module accounts are capable of sending/receiving tokens to and from`auth.Account`s and other module accounts. This design replaces previous\ -alternative designs where, to hold tokens, modules would burn the incoming\ -tokens from the sender account, and then track those tokens internally. Later,\ -in order to send tokens, the module would need to effectively mint tokens\ -within a destination account. The new design removes duplicate logic between\ +The supply functionality introduces a new type of `auth.Account` which can be used by +modules to allocate tokens and in special cases mint or burn tokens. At a base +level these module accounts are capable of sending/receiving tokens to and from +`auth.Account`s and other module accounts. This design replaces previous +alternative designs where, to hold tokens, modules would burn the incoming +tokens from the sender account, and then track those tokens internally. Later, +in order to send tokens, the module would need to effectively mint tokens +within a destination account. The new design removes duplicate logic between modules to perform this accounting. The `ModuleAccount` interface is defined as follows: @@ -79,23 +80,24 @@ type ModuleAccount interface { } ``` -> **WARNING!**\ +> **WARNING!** > Any module or message handler that allows either direct or indirect sending of funds must explicitly guarantee those funds cannot be sent to module accounts (unless allowed). -The supply `Keeper` also introduces new wrapper functions for the auth `Keeper`\ -and the bank `Keeper` that are related to `ModuleAccount`s in order to be able\ +The supply `Keeper` also introduces new wrapper functions for the auth `Keeper` +and the bank `Keeper` that are related to `ModuleAccount`s in order to be able to: * Get and set `ModuleAccount`s by providing the `Name`. -* Send coins from and to other `ModuleAccount`s or standard `Account`s\ +* Send coins from and to other `ModuleAccount`s or standard `Account`s (`BaseAccount` or `VestingAccount`) by passing only the `Name`. * `Mint` or `Burn` coins for a `ModuleAccount` (restricted to its permissions). ### Permissions -Each `ModuleAccount` has a different set of permissions that provide different\ -object capabilities to perform certain actions. Permissions need to be\ -registered upon the creation of the supply `Keeper` so that every time a`ModuleAccount` calls the allowed functions, the `Keeper` can lookup the\ +Each `ModuleAccount` has a different set of permissions that provide different +object capabilities to perform certain actions. Permissions need to be +registered upon the creation of the supply `Keeper` so that every time a +`ModuleAccount` calls the allowed functions, the `Keeper` can lookup the permissions to that specific account and perform or not perform the action. The available permissions are: @@ -113,7 +115,7 @@ The `x/bank` module keeps state of the following primary objects: 3. The total supply of all balances 4. Information on which denominations are allowed to be sent. -In addition, the `x/bank` module keeps the following indexes to manage the\ +In addition, the `x/bank` module keeps the following indexes to manage the aforementioned state: * Supply Index: `0x0 | byte(denom) -> byte(amount)` @@ -123,32 +125,33 @@ aforementioned state: ## Params -The bank module stores it's params in state with the prefix of `0x05`,\ +The bank module stores it's params in state with the prefix of `0x05`, it can be updated with governance or the address with authority. * Params: `0x05 | ProtocolBuffer(Params)` -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/bank/v1beta1/bank.proto#L12-L23 ``` ## Keepers -The bank module provides these exported keeper interfaces that can be\ -passed to other modules that read or update account balances. Modules\ -should use the least-permissive interface that provides the functionality they\ +The bank module provides these exported keeper interfaces that can be +passed to other modules that read or update account balances. Modules +should use the least-permissive interface that provides the functionality they require. -Best practices dictate careful review of `bank` module code to ensure that\ +Best practices dictate careful review of `bank` module code to ensure that permissions are limited in the way that you expect. ### Denied Addresses -The `x/bank` module accepts a map of addresses that are considered blocklisted\ -from directly and explicitly receiving funds through means such as `MsgSend` and`MsgMultiSend` and direct API calls like `SendCoinsFromModuleToAccount`. +The `x/bank` module accepts a map of addresses that are considered blocklisted +from directly and explicitly receiving funds through means such as `MsgSend` and +`MsgMultiSend` and direct API calls like `SendCoinsFromModuleToAccount`. -Typically, these addresses are module accounts. If these addresses receive funds\ -outside the expected rules of the state machine, invariants are likely to be\ +Typically, these addresses are module accounts. If these addresses receive funds +outside the expected rules of the state machine, invariants are likely to be broken and could result in a halted network. By providing the `x/bank` module with a blocklisted set of addresses, an error occurs for the operation if a user or client attempts to directly or indirectly send funds to a blocklisted account, for example, by using [IBC](https://ibc.cosmos.network). @@ -224,7 +227,7 @@ type Keeper interface { ### SendKeeper -The send keeper provides access to account balances and the ability to transfer coins between\ +The send keeper provides access to account balances and the ability to transfer coins between accounts. The send keeper does not alter the total supply (mint or burn coins). ```go @@ -266,18 +269,20 @@ The `SendKeeper` applies a `SendRestrictionFn` before each transfer of funds. type SendRestrictionFn func(ctx context.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) (newToAddr sdk.AccAddress, err error) ``` -After the `SendKeeper` (or `BaseKeeper`) has been created, send restrictions can be added to it using the `AppendSendRestriction` or `PrependSendRestriction` functions.\ -Both functions compose the provided restriction with any previously provided restrictions.`AppendSendRestriction` adds the provided restriction to be run after any previously provided send restrictions.`PrependSendRestriction` adds the restriction to be run before any previously provided send restrictions.\ +After the `SendKeeper` (or `BaseKeeper`) has been created, send restrictions can be added to it using the `AppendSendRestriction` or `PrependSendRestriction` functions. +Both functions compose the provided restriction with any previously provided restrictions. +`AppendSendRestriction` adds the provided restriction to be run after any previously provided send restrictions. +`PrependSendRestriction` adds the restriction to be run before any previously provided send restrictions. The composition will short-circuit when an error is encountered. I.e. if the first one returns an error, the second is not run. -During `SendCoins`, the send restriction is applied after coins are removed from the from address, but before adding them to the to address.\ +During `SendCoins`, the send restriction is applied after coins are removed from the from address, but before adding them to the to address. During `InputOutputCoins`, the send restriction is applied after the input coins are removed and once for each output before the funds are added. A send restriction function should make use of a custom value in the context to allow bypassing that specific restriction. Send Restrictions are not placed on `ModuleToAccount` or `ModuleToModule` transfers. This is done due to modules needing to move funds to user accounts and other module accounts. This is a design decision to allow for more flexibility in the state machine. The state machine should be able to move funds between module accounts and user accounts without restrictions. -Secondly this limitation would limit the usage of the state machine even for itself. users would not be able to receive rewards, not be able to move funds between module accounts. In the case that a user sends funds from a user account to the community pool and then a governance proposal is used to get those tokens into the users account this would fall under the discretion of the app chain developer to what they would like to do here. We can not make strong assumptions here.\ +Secondly this limitation would limit the usage of the state machine even for itself. users would not be able to receive rewards, not be able to move funds between module accounts. In the case that a user sends funds from a user account to the community pool and then a governance proposal is used to get those tokens into the users account this would fall under the discretion of the app chain developer to what they would like to do here. We can not make strong assumptions here. Thirdly, this issue could lead into a chain halt if a token is disabled and the token is moved in the begin/endblock. This is the last reason we see the current change and more damaging then beneficial for users. For example, in your module's keeper package, you'd define the send restriction function: @@ -369,7 +374,7 @@ type ViewKeeper interface { Send coins from one address to another. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/bank/v1beta1/tx.proto#L38-L53 ``` @@ -382,7 +387,7 @@ The message will fail under the following conditions: Send coins from one sender and to a series of different address. If any of the receiving addresses do not correspond to an existing account, a new account is created. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/bank/v1beta1/tx.proto#L58-L69 ``` @@ -395,9 +400,9 @@ The message will fail under the following conditions: ### MsgUpdateParams -The `bank` module params can be updated through `MsgUpdateParams`, which can be done using governance proposal. The signer will always be the `gov` module account address. +The `bank` module params can be updated through `MsgUpdateParams`, which can be done using governance proposal. The signer will always be the `gov` module account address. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/bank/v1beta1/tx.proto#L74-L88 ``` @@ -409,7 +414,7 @@ The message handling can fail if: Used with the x/gov module to set create/edit SendEnabled entries. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/bank/v1beta1/tx.proto#L96-L117 ``` @@ -572,13 +577,14 @@ The bank module contains the following parameters ### SendEnabled -The SendEnabled parameter is now deprecated and not to be use. It is replaced\ +The SendEnabled parameter is now deprecated and not to be use. It is replaced with state store records. + ### DefaultSendEnabled -The default send enabled value controls send transfer capability for all\ -coin denominations unless specifically included in the array of `SendEnabled`\ +The default send enabled value controls send transfer capability for all +coin denominations unless specifically included in the array of `SendEnabled` parameters. ## Client @@ -595,7 +601,7 @@ The `query` commands allow users to query `bank` state. simd query bank --help ``` -**balances** +##### balances The `balances` command allows users to query account balances by address. @@ -620,7 +626,7 @@ pagination: total: "0" ``` -**denom-metadata** +##### denom-metadata The `denom-metadata` command allows users to query metadata for coin denominations. A user can query metadata for a single denomination using the `--denom` flag or all denominations without it. @@ -649,7 +655,7 @@ metadata: symbol: STK ``` -**total** +##### total The `total` command allows users to query the total supply of coins. A user can query the total supply for a single coin using the `--denom` flag or all coins without it. @@ -670,7 +676,7 @@ amount: "10000000000" denom: stake ``` -**send-enabled** +##### send-enabled The `send-enabled` command allows users to query for all or some SendEnabled entries. @@ -704,7 +710,7 @@ The `tx` commands allow users to interact with the `bank` module. simd tx bank --help ``` -**send** +##### send The `send` command allows users to send funds from one account to another. diff --git a/.gitbook/developers-native/core/circuit.mdx b/.gitbook/developers-native/core/circuit/index.md similarity index 100% rename from .gitbook/developers-native/core/circuit.mdx rename to .gitbook/developers-native/core/circuit/index.md diff --git a/.gitbook/developers-native/core/consensus.mdx b/.gitbook/developers-native/core/consensus/index.md similarity index 100% rename from .gitbook/developers-native/core/consensus.mdx rename to .gitbook/developers-native/core/consensus/index.md diff --git a/.gitbook/developers-native/core/crisis.mdx b/.gitbook/developers-native/core/crisis/index.md similarity index 100% rename from .gitbook/developers-native/core/crisis.mdx rename to .gitbook/developers-native/core/crisis/index.md diff --git a/.gitbook/developers-native/core/distribution.mdx b/.gitbook/developers-native/core/distribution/index.md similarity index 83% rename from .gitbook/developers-native/core/distribution.mdx rename to .gitbook/developers-native/core/distribution/index.md index 152b806..32858fd 100644 --- a/.gitbook/developers-native/core/distribution.mdx +++ b/.gitbook/developers-native/core/distribution/index.md @@ -2,139 +2,141 @@ sidebar_position: 1 --- -# Distribution +# `x/distribution` ## Overview -This _simple_ distribution mechanism describes a functional way to passively\ -distribute rewards between validators and delegators. Note that this mechanism does\ -not distribute funds in as precisely as active reward distribution mechanisms and\ +This _simple_ distribution mechanism describes a functional way to passively +distribute rewards between validators and delegators. Note that this mechanism does +not distribute funds in as precisely as active reward distribution mechanisms and will therefore be upgraded in the future. -The mechanism operates as follows. Collected rewards are pooled globally and\ -divided out passively to validators and delegators. Each validator has the\ -opportunity to charge commission to the delegators on the rewards collected on\ -behalf of the delegators. Fees are collected directly into a global reward pool\ -and validator proposer-reward pool. Due to the nature of passive accounting,\ -whenever changes to parameters which affect the rate of reward distribution\ +The mechanism operates as follows. Collected rewards are pooled globally and +divided out passively to validators and delegators. Each validator has the +opportunity to charge commission to the delegators on the rewards collected on +behalf of the delegators. Fees are collected directly into a global reward pool +and validator proposer-reward pool. Due to the nature of passive accounting, +whenever changes to parameters which affect the rate of reward distribution occurs, withdrawal of rewards must also occur. -* Whenever withdrawing, one must withdraw the maximum amount they are entitled\ - to, leaving nothing in the pool. -* Whenever bonding, unbonding, or re-delegating tokens to an existing account, a\ - full withdrawal of the rewards must occur (as the rules for lazy accounting\ - change). -* Whenever a validator chooses to change the commission on rewards, all accumulated\ - commission rewards must be simultaneously withdrawn. +* Whenever withdrawing, one must withdraw the maximum amount they are entitled + to, leaving nothing in the pool. +* Whenever bonding, unbonding, or re-delegating tokens to an existing account, a + full withdrawal of the rewards must occur (as the rules for lazy accounting + change). +* Whenever a validator chooses to change the commission on rewards, all accumulated + commission rewards must be simultaneously withdrawn. The above scenarios are covered in `hooks.md`. -The distribution mechanism outlined herein is used to lazily distribute the\ +The distribution mechanism outlined herein is used to lazily distribute the following rewards between validators and associated delegators: * multi-token fees to be socially distributed * inflated staked asset provisions * validator commission on all rewards earned by their delegators stake -Fees are pooled within a global pool. The mechanisms used allow for validators\ +Fees are pooled within a global pool. The mechanisms used allow for validators and delegators to independently and lazily withdraw their rewards. ## Shortcomings -As a part of the lazy computations, each delegator holds an accumulation term\ -specific to each validator which is used to estimate what their approximate\ +As a part of the lazy computations, each delegator holds an accumulation term +specific to each validator which is used to estimate what their approximate fair portion of tokens held in the global fee pool is owed to them. -``` +```text entitlement = delegator-accumulation / all-delegators-accumulation ``` -Under the circumstance that there was constant and equal flow of incoming\ -reward tokens every block, this distribution mechanism would be equal to the\ -active distribution (distribute individually to all delegators each block).\ -However, this is unrealistic so deviations from the active distribution will\ -occur based on fluctuations of incoming reward tokens as well as timing of\ +Under the circumstance that there was constant and equal flow of incoming +reward tokens every block, this distribution mechanism would be equal to the +active distribution (distribute individually to all delegators each block). +However, this is unrealistic so deviations from the active distribution will +occur based on fluctuations of incoming reward tokens as well as timing of reward withdrawal by other delegators. -If you happen to know that incoming rewards are about to significantly increase,\ -you are incentivized to not withdraw until after this event, increasing the\ -worth of your existing _accum_. See [#2764](https://github.com/cosmos/cosmos-sdk/issues/2764)\ +If you happen to know that incoming rewards are about to significantly increase, +you are incentivized to not withdraw until after this event, increasing the +worth of your existing _accum_. See [#2764](https://github.com/cosmos/cosmos-sdk/issues/2764) for further details. ## Effect on Staking -Charging commission on Atom provisions while also allowing for Atom-provisions\ -to be auto-bonded (distributed directly to the validators bonded stake) is\ -problematic within BPoS. Fundamentally, these two mechanisms are mutually\ -exclusive. If both commission and auto-bonding mechanisms are simultaneously\ -applied to the staking-token then the distribution of staking-tokens between\ -any validator and its delegators will change with each block. This then\ -necessitates a calculation for each delegation records for each block -\ +Charging commission on Atom provisions while also allowing for Atom-provisions +to be auto-bonded (distributed directly to the validators bonded stake) is +problematic within BPoS. Fundamentally, these two mechanisms are mutually +exclusive. If both commission and auto-bonding mechanisms are simultaneously +applied to the staking-token then the distribution of staking-tokens between +any validator and its delegators will change with each block. This then +necessitates a calculation for each delegation records for each block - which is considered computationally expensive. -In conclusion, we can only have Atom commission and unbonded atoms\ -provisions or bonded atom provisions with no Atom commission, and we elect to\ -implement the former. Stakeholders wishing to rebond their provisions may elect\ +In conclusion, we can only have Atom commission and unbonded atoms +provisions or bonded atom provisions with no Atom commission, and we elect to +implement the former. Stakeholders wishing to rebond their provisions may elect to set up a script to periodically withdraw and rebond rewards. ## Contents -* [Concepts](./#concepts) -* [State](./#state) - * [FeePool](./#feepool) - * [Validator Distribution](./#validator-distribution) - * [Delegation Distribution](./#delegation-distribution) - * [Params](./#params) -* [Begin Block](./#begin-block) -* [Messages](./#messages) -* [Hooks](./#hooks) -* [Events](./#events) -* [Parameters](./#parameters) -* [Client](./#client) - * [CLI](./#cli) - * [gRPC](./#grpc) +* [Concepts](#concepts) +* [State](#state) + * [FeePool](#feepool) + * [Validator Distribution](#validator-distribution) + * [Delegation Distribution](#delegation-distribution) + * [Params](#params) +* [Begin Block](#begin-block) +* [Messages](#messages) +* [Hooks](#hooks) +* [Events](#events) +* [Parameters](#parameters) +* [Client](#client) + * [CLI](#cli) + * [gRPC](#grpc) ## Concepts In Proof of Stake (PoS) blockchains, rewards gained from transaction fees are paid to validators. The fee distribution module fairly distributes the rewards to the validators' constituent delegators. -Rewards are calculated per period. The period is updated each time a validator's delegation changes, for example, when the validator receives a new delegation.\ -The rewards for a single validator can then be calculated by taking the total rewards for the period before the delegation started, minus the current total rewards.\ +Rewards are calculated per period. The period is updated each time a validator's delegation changes, for example, when the validator receives a new delegation. +The rewards for a single validator can then be calculated by taking the total rewards for the period before the delegation started, minus the current total rewards. To learn more, see the [F1 Fee Distribution paper](https://github.com/cosmos/cosmos-sdk/tree/main/docs/spec/fee_distribution/f1_fee_distr.pdf). -The commission to the validator is paid when the validator is removed or when the validator requests a withdrawal.\ +The commission to the validator is paid when the validator is removed or when the validator requests a withdrawal. The commission is calculated and incremented at every `BeginBlock` operation to update accumulated fee amounts. -The rewards to a delegator are distributed when the delegation is changed or removed, or a withdrawal is requested.\ +The rewards to a delegator are distributed when the delegation is changed or removed, or a withdrawal is requested. Before rewards are distributed, all slashes to the validator that occurred during the current delegation are applied. ### Reference Counting in F1 Fee Distribution In F1 fee distribution, the rewards a delegator receives are calculated when their delegation is withdrawn. This calculation must read the terms of the summation of rewards divided by the share of tokens from the period which they ended when they delegated, and the final period that was created for the withdrawal. -Additionally, as slashes change the amount of tokens a delegation will have (but we calculate this lazily,\ -only when a delegator un-delegates), we must calculate rewards in separate periods before / after any slashes\ -which occurred in between when a delegator delegated and when they withdrew their rewards. Thus slashes, like\ +Additionally, as slashes change the amount of tokens a delegation will have (but we calculate this lazily, +only when a delegator un-delegates), we must calculate rewards in separate periods before / after any slashes +which occurred in between when a delegator delegated and when they withdrew their rewards. Thus slashes, like delegations, reference the period which was ended by the slash event. -All stored historical rewards records for periods which are no longer referenced by any delegations\ -or any slashes can thus be safely removed, as they will never be read (future delegations and future\ -slashes will always reference future periods). This is implemented by tracking a `ReferenceCount`\ -along with each historical reward storage entry. Each time a new object (delegation or slash)\ -is created which might need to reference the historical record, the reference count is incremented.\ -Each time one object which previously needed to reference the historical record is deleted, the reference\ +All stored historical rewards records for periods which are no longer referenced by any delegations +or any slashes can thus be safely removed, as they will never be read (future delegations and future +slashes will always reference future periods). This is implemented by tracking a `ReferenceCount` +along with each historical reward storage entry. Each time a new object (delegation or slash) +is created which might need to reference the historical record, the reference count is incremented. +Each time one object which previously needed to reference the historical record is deleted, the reference count is decremented. If the reference count hits zero, the historical record is deleted. ## State ### FeePool -All globally tracked parameters for distribution are stored within`FeePool`. Rewards are collected and added to the reward pool and\ +All globally tracked parameters for distribution are stored within +`FeePool`. Rewards are collected and added to the reward pool and distributed to validators/delegators from here. -Note that the reward pool holds decimal coins (`DecCoins`) to allow\ -for fractions of coins to be received from operations like inflation.\ -When coins are distributed from the pool they are truncated back to`sdk.Coins` which are non-decimal. +Note that the reward pool holds decimal coins (`DecCoins`) to allow +for fractions of coins to be received from operations like inflation. +When coins are distributed from the pool they are truncated back to +`sdk.Coins` which are non-decimal. * FeePool: `0x00 -> ProtocolBuffer(FeePool)` @@ -148,7 +150,7 @@ type DecCoin struct { } ``` -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/distribution/v1beta1/distribution.proto#L116-L123 ``` @@ -172,10 +174,10 @@ type ValidatorDistInfo struct { ### Delegation Distribution -Each delegation distribution only needs to record the height at which it last\ -withdrew fees. Because a delegation must withdraw fees each time it's\ -properties change (aka bonded tokens etc.) its properties will remain constant\ -and the delegator's _accumulation_ factor can be calculated passively knowing\ +Each delegation distribution only needs to record the height at which it last +withdrew fees. Because a delegation must withdraw fees each time it's +properties change (aka bonded tokens etc.) its properties will remain constant +and the delegator's _accumulation_ factor can be calculated passively knowing only the height of the last withdrawal and its current properties. * DelegationDistInfo: `0x02 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValOperatorAddrLen (1 byte) | ValOperatorAddr -> ProtocolBuffer(delegatorDist)` @@ -188,20 +190,20 @@ type DelegationDistInfo struct { ### Params -The distribution module stores it's params in state with the prefix of `0x09`,\ +The distribution module stores it's params in state with the prefix of `0x09`, it can be updated with governance or the address with authority. * Params: `0x09 | ProtocolBuffer(Params)` -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/distribution/v1beta1/distribution.proto#L12-L42 ``` ## Begin Block -At each `BeginBlock`, all fees received in the previous block are transferred to\ -the distribution `ModuleAccount` account. When a delegator or validator\ -withdraws their rewards, they are taken out of the `ModuleAccount`. During begin\ +At each `BeginBlock`, all fees received in the previous block are transferred to +the distribution `ModuleAccount` account. When a delegator or validator +withdraws their rewards, they are taken out of the `ModuleAccount`. During begin block, the different claims on the fees collected are updated as follows: * The reserve community tax is charged. @@ -209,26 +211,28 @@ block, the different claims on the fees collected are updated as follows: ### The Distribution Scheme -See [params](./#params) for description of parameters. +See [params](#params) for description of parameters. -Let `fees` be the total fees collected in the previous block, including\ -inflationary rewards to the stake. All fees are collected in a specific module\ -account during the block. During `BeginBlock`, they are sent to the`"distribution"` `ModuleAccount`. No other sending of tokens occurs. Instead, the\ -rewards each account is entitled to are stored, and withdrawals can be triggered\ -through the messages `FundCommunityPool`, `WithdrawValidatorCommission` and`WithdrawDelegatorReward`. +Let `fees` be the total fees collected in the previous block, including +inflationary rewards to the stake. All fees are collected in a specific module +account during the block. During `BeginBlock`, they are sent to the +`"distribution"` `ModuleAccount`. No other sending of tokens occurs. Instead, the +rewards each account is entitled to are stored, and withdrawals can be triggered +through the messages `FundCommunityPool`, `WithdrawValidatorCommission` and +`WithdrawDelegatorReward`. #### Reward to the Community Pool -The community pool gets `community_tax * fees`, plus any remaining dust after\ -validators get their rewards that are always rounded down to the nearest\ +The community pool gets `community_tax * fees`, plus any remaining dust after +validators get their rewards that are always rounded down to the nearest integer value. #### Reward To the Validators -The proposer receives no extra rewards. All fees are distributed among all the\ +The proposer receives no extra rewards. All fees are distributed among all the bonded validators, including the proposer, in proportion to their consensus power. -``` +```text powFrac = validator power / total bonded validator power voteMul = 1 - community_tax ``` @@ -237,28 +241,29 @@ All validators receive `fees * voteMul * powFrac`. #### Rewards to Delegators -Each validator's rewards are distributed to its delegators. The validator also\ -has a self-delegation that is treated like a regular delegation in\ +Each validator's rewards are distributed to its delegators. The validator also +has a self-delegation that is treated like a regular delegation in distribution calculations. -The validator sets a commission rate. The commission rate is flexible, but each\ +The validator sets a commission rate. The commission rate is flexible, but each validator sets a maximum rate and a maximum daily increase. These maximums cannot be exceeded and protect delegators from sudden increases of validator commission rates to prevent validators from taking all of the rewards. -The outstanding rewards that the operator is entitled to are stored in`ValidatorAccumulatedCommission`, while the rewards the delegators are entitled\ -to are stored in `ValidatorCurrentRewards`. The [F1 fee distribution scheme](./#concepts) is used to calculate the rewards per delegator as they\ +The outstanding rewards that the operator is entitled to are stored in +`ValidatorAccumulatedCommission`, while the rewards the delegators are entitled +to are stored in `ValidatorCurrentRewards`. The [F1 fee distribution scheme](#concepts) is used to calculate the rewards per delegator as they withdraw or update their delegation, and is thus not handled in `BeginBlock`. #### Example Distribution -For this example distribution, the underlying consensus engine selects block proposers in\ +For this example distribution, the underlying consensus engine selects block proposers in proportion to their power relative to the entire bonded power. -All validators are equally performant at including pre-commits in their proposed\ -blocks. Then hold `(pre_commits included) / (total bonded validator power)`\ -constant so that the amortized block reward for the validator is `( validator power / total bonded power) * (1 - community tax rate)` of\ +All validators are equally performant at including pre-commits in their proposed +blocks. Then hold `(pre_commits included) / (total bonded validator power)` +constant so that the amortized block reward for the validator is `( validator power / total bonded power) * (1 - community tax rate)` of the total rewards. Consequently, the reward for a single delegator is: -``` +```text (delegator proportion of the validator power / validator power) * (validator power / total bonded power) * (1 - community tax rate) * (1 - validator commission rate) = (delegator proportion of the validator power / total bonded power) * (1 - @@ -269,14 +274,14 @@ community tax rate) * (1 - validator commission rate) ### MsgSetWithdrawAddress -By default, the withdraw address is the delegator address. To change its withdraw address, a delegator must send a `MsgSetWithdrawAddress` message.\ +By default, the withdraw address is the delegator address. To change its withdraw address, a delegator must send a `MsgSetWithdrawAddress` message. Changing the withdraw address is possible only if the parameter `WithdrawAddrEnabled` is set to `true`. The withdraw address cannot be any of the module accounts. These accounts are blocked from being withdraw addresses by being added to the distribution keeper's `blockedAddrs` array at initialization. Response: -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/distribution/v1beta1/tx.proto#L49-L60 ``` @@ -295,21 +300,21 @@ func (k Keeper) SetWithdrawAddr(ctx context.Context, delegatorAddr sdk.AccAddres ### MsgWithdrawDelegatorReward -A delegator can withdraw its rewards.\ -Internally in the distribution module, this transaction simultaneously removes the previous delegation with associated rewards, the same as if the delegator simply started a new delegation of the same value.\ -The rewards are sent immediately from the distribution `ModuleAccount` to the withdraw address.\ -Any remainder (truncated decimals) are sent to the community pool.\ -The starting height of the delegation is set to the current validator period, and the reference count for the previous period is decremented.\ +A delegator can withdraw its rewards. +Internally in the distribution module, this transaction simultaneously removes the previous delegation with associated rewards, the same as if the delegator simply started a new delegation of the same value. +The rewards are sent immediately from the distribution `ModuleAccount` to the withdraw address. +Any remainder (truncated decimals) are sent to the community pool. +The starting height of the delegation is set to the current validator period, and the reference count for the previous period is decremented. The amount withdrawn is deducted from the `ValidatorOutstandingRewards` variable for the validator. -In the F1 distribution, the total rewards are calculated per validator period, and a delegator receives a piece of those rewards in proportion to their stake in the validator.\ -In basic F1, the total rewards that all the delegators are entitled to between to periods is calculated the following way.\ -Let `R(X)` be the total accumulated rewards up to period `X` divided by the tokens staked at that time. The delegator allocation is `R(X) * delegator_stake`.\ -Then the rewards for all the delegators for staking between periods `A` and `B` are `(R(B) - R(A)) * total stake`.\ +In the F1 distribution, the total rewards are calculated per validator period, and a delegator receives a piece of those rewards in proportion to their stake in the validator. +In basic F1, the total rewards that all the delegators are entitled to between to periods is calculated the following way. +Let `R(X)` be the total accumulated rewards up to period `X` divided by the tokens staked at that time. The delegator allocation is `R(X) * delegator_stake`. +Then the rewards for all the delegators for staking between periods `A` and `B` are `(R(B) - R(A)) * total stake`. However, these calculated rewards don't account for slashing. -Taking the slashes into account requires iteration.\ -Let `F(X)` be the fraction a validator is to be slashed for a slashing event that happened at period `X`.\ +Taking the slashes into account requires iteration. +Let `F(X)` be the fraction a validator is to be slashed for a slashing event that happened at period `X`. If the validator was slashed at periods `P1, ..., PN`, where `A < P1`, `PN < B`, the distribution module calculates the individual delegator's rewards, `T(A, B)`, as follows: ```go @@ -323,20 +328,20 @@ for P in P1, ..., PN`: rewards = rewards + (R(B) - R(PN)) * stake ``` -The historical rewards are calculated retroactively by playing back all the slashes and then attenuating the delegator's stake at each step.\ +The historical rewards are calculated retroactively by playing back all the slashes and then attenuating the delegator's stake at each step. The final calculated stake is equivalent to the actual staked coins in the delegation with a margin of error due to rounding errors. Response: -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/distribution/v1beta1/tx.proto#L66-L77 ``` ### WithdrawValidatorCommission -The validator can send the WithdrawValidatorCommission message to withdraw their accumulated commission.\ -The commission is calculated in every block during `BeginBlock`, so no iteration is required to withdraw.\ -The amount withdrawn is deducted from the `ValidatorOutstandingRewards` variable for the validator.\ +The validator can send the WithdrawValidatorCommission message to withdraw their accumulated commission. +The commission is calculated in every block during `BeginBlock`, so no iteration is required to withdraw. +The amount withdrawn is deducted from the `ValidatorOutstandingRewards` variable for the validator. Only integer amounts can be sent. If the accumulated awards have decimals, the amount is truncated before the withdrawal is sent, and the remainder is left to be withdrawn later. ### FundCommunityPool @@ -372,7 +377,7 @@ These operations take place during many different messages. #### Initialize delegation -Each time a delegation is changed, the rewards are withdrawn and the delegation is reinitialized.\ +Each time a delegation is changed, the rewards are withdrawn and the delegation is reinitialized. Initializing a delegation increments the validator period and keeps track of the starting period of the delegation. ```go @@ -399,7 +404,7 @@ func (k Keeper) initializeDelegation(ctx context.Context, val sdk.ValAddress, de Distribution module params can be updated through `MsgUpdateParams`, which can be done using governance proposal and the signer will always be gov module account address. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/distribution/v1beta1/tx.proto#L133-L147 ``` @@ -417,15 +422,15 @@ Available hooks that can be called by and from this module. #### Before -* The delegation rewards are withdrawn to the withdraw address of the delegator.\ +* The delegation rewards are withdrawn to the withdraw address of the delegator. The rewards include the current period and exclude the starting period. -* The validator period is incremented.\ +* The validator period is incremented. The validator period is incremented because the validator's power and share distribution might have changed. * The reference count for the delegator's starting period is decremented. #### After -The starting height of the delegation is set to the previous period.\ +The starting height of the delegation is set to the previous period. Because of the `Before`-hook, this period is the last period for which the delegator was rewarded. ### Validator created @@ -446,20 +451,20 @@ By default, all values are set to a `0`, except period, which is set to `1`. * triggered-by: `staking.RemoveValidator` -Outstanding commission is sent to the validator's self-delegation withdrawal address.\ +Outstanding commission is sent to the validator's self-delegation withdrawal address. Remaining delegator rewards get sent to the community fee pool. -Note: The validator gets removed only when it has no remaining delegations.\ -At that time, all outstanding delegator rewards will have been withdrawn.\ +Note: The validator gets removed only when it has no remaining delegations. +At that time, all outstanding delegator rewards will have been withdrawn. Any remaining rewards are dust amounts. ### Validator is slashed * triggered-by: `staking.Slash` -* The current validator period reference count is incremented.\ +* The current validator period reference count is incremented. The reference count is incremented because the slash event has created a reference to it. * The validator period is incremented. -* The slash event is stored for later use.\ +* The slash event is stored for later use. The slash event will be referenced when calculating delegator rewards. ## Events @@ -468,60 +473,60 @@ The distribution module emits the following events: ### BeginBlocker -| Type | Attribute Key | Attribute Value | -| ---------------- | ------------- | ------------------ | -| proposer\_reward | validator | {validatorAddress} | -| proposer\_reward | reward | {proposerReward} | -| commission | amount | {commissionAmount} | -| commission | validator | {validatorAddress} | -| rewards | amount | {rewardAmount} | -| rewards | validator | {validatorAddress} | +| Type | Attribute Key | Attribute Value | +|-----------------|---------------|--------------------| +| proposer_reward | validator | {validatorAddress} | +| proposer_reward | reward | {proposerReward} | +| commission | amount | {commissionAmount} | +| commission | validator | {validatorAddress} | +| rewards | amount | {rewardAmount} | +| rewards | validator | {validatorAddress} | ### Handlers #### MsgSetWithdrawAddress -| Type | Attribute Key | Attribute Value | -| ---------------------- | ----------------- | ---------------------- | -| set\_withdraw\_address | withdraw\_address | {withdrawAddress} | -| message | module | distribution | -| message | action | set\_withdraw\_address | -| message | sender | {senderAddress} | +| Type | Attribute Key | Attribute Value | +|----------------------|------------------|----------------------| +| set_withdraw_address | withdraw_address | {withdrawAddress} | +| message | module | distribution | +| message | action | set_withdraw_address | +| message | sender | {senderAddress} | #### MsgWithdrawDelegatorReward -| Type | Attribute Key | Attribute Value | -| ----------------- | ------------- | --------------------------- | -| withdraw\_rewards | amount | {rewardAmount} | -| withdraw\_rewards | validator | {validatorAddress} | -| message | module | distribution | -| message | action | withdraw\_delegator\_reward | -| message | sender | {senderAddress} | +| Type | Attribute Key | Attribute Value | +|---------|---------------|---------------------------| +| withdraw_rewards | amount | {rewardAmount} | +| withdraw_rewards | validator | {validatorAddress} | +| message | module | distribution | +| message | action | withdraw_delegator_reward | +| message | sender | {senderAddress} | #### MsgWithdrawValidatorCommission -| Type | Attribute Key | Attribute Value | -| -------------------- | ------------- | ------------------------------- | -| withdraw\_commission | amount | {commissionAmount} | -| message | module | distribution | -| message | action | withdraw\_validator\_commission | -| message | sender | {senderAddress} | +| Type | Attribute Key | Attribute Value | +|------------|---------------|-------------------------------| +| withdraw_commission | amount | {commissionAmount} | +| message | module | distribution | +| message | action | withdraw_validator_commission | +| message | sender | {senderAddress} | ## Parameters The distribution module contains the following parameters: -| Key | Type | Example | -| ------------------- | ------------ | --------------------------- | -| communitytax | string (dec) | "0.020000000000000000" \[0] | -| withdrawaddrenabled | bool | true | +| Key | Type | Example | +| ------------------- | ------------ | -------------------------- | +| communitytax | string (dec) | "0.020000000000000000" [0] | +| withdrawaddrenabled | bool | true | -* \[0] `communitytax` must be positive and cannot exceed 1.00. +* [0] `communitytax` must be positive and cannot exceed 1.00. * `baseproposerreward` and `bonusproposerreward` were parameters that are deprecated in v0.47 and are not used. -:::note\ -The reserve pool is the pool of collected funds for use by governance taken via the `CommunityTax`.\ -Currently with the Cosmos SDK, tokens collected by the CommunityTax are accounted for but unspendable.\ +:::note +The reserve pool is the pool of collected funds for use by governance taken via the `CommunityTax`. +Currently with the Cosmos SDK, tokens collected by the CommunityTax are accounted for but unspendable. ::: ## Client @@ -538,7 +543,7 @@ The `query` commands allow users to query `distribution` state. simd query distribution --help ``` -**commission** +##### commission The `commission` command allows users to query validator commission rewards by address. @@ -560,7 +565,7 @@ commission: denom: stake ``` -**community-pool** +##### community-pool The `community-pool` command allows users to query all coin balances within the community pool. @@ -582,7 +587,7 @@ pool: denom: stake ``` -**params** +##### params The `params` command allows users to query the parameters of the `distribution` module. @@ -605,7 +610,7 @@ community_tax: "0.020000000000000000" withdraw_addr_enabled: true ``` -**rewards** +##### rewards The `rewards` command allows users to query delegator rewards. Users can optionally include the validator address to query rewards earned from a specific validator. @@ -632,7 +637,7 @@ total: denom: stake ``` -**slashes** +##### slashes The `slashes` command allows users to query all slashes for a given block range. @@ -657,7 +662,7 @@ slashes: fraction: "0.009999999999999999" ``` -**validator-outstanding-rewards** +##### validator-outstanding-rewards The `validator-outstanding-rewards` command allows users to query all outstanding (un-withdrawn) rewards for a validator and all their delegations. @@ -679,7 +684,7 @@ rewards: denom: stake ``` -**validator-distribution-info** +##### validator-distribution-info The `validator-distribution-info` command allows users to query validator commission and self-delegation rewards for validator. @@ -1042,4 +1047,3 @@ Example Output: ] } ``` -```` diff --git a/.gitbook/developers-native/core/evidence.mdx b/.gitbook/developers-native/core/evidence/index.md similarity index 82% rename from .gitbook/developers-native/core/evidence.mdx rename to .gitbook/developers-native/core/evidence/index.md index 3ef0d59..cfd35bf 100644 --- a/.gitbook/developers-native/core/evidence.mdx +++ b/.gitbook/developers-native/core/evidence/index.md @@ -2,45 +2,48 @@ sidebar_position: 1 --- -# Evidence - -* [Concepts](./#concepts) -* [State](./#state) -* [Messages](./#messages) -* [Events](./#events) -* [Parameters](./#parameters) -* [BeginBlock](./#beginblock) -* [Client](./#client) - * [CLI](./#cli) - * [REST](./#rest) - * [gRPC](./#grpc) +# `x/evidence` + +* [Concepts](#concepts) +* [State](#state) +* [Messages](#messages) +* [Events](#events) +* [Parameters](#parameters) +* [BeginBlock](#beginblock) +* [Client](#client) + * [CLI](#cli) + * [REST](#rest) + * [gRPC](#grpc) ## Abstract -`x/evidence` is an implementation of a Cosmos SDK module, per [ADR 009](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-009-evidence-module.md),\ -that allows for the submission and handling of arbitrary evidence of misbehavior such\ +`x/evidence` is an implementation of a Cosmos SDK module, per [ADR 009](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-009-evidence-module.md), +that allows for the submission and handling of arbitrary evidence of misbehavior such as equivocation and counterfactual signing. -The evidence module differs from standard evidence handling which typically expects the\ -underlying consensus engine, e.g. CometBFT, to automatically submit evidence when\ -it is discovered by allowing clients and foreign chains to submit more complex evidence\ +The evidence module differs from standard evidence handling which typically expects the +underlying consensus engine, e.g. CometBFT, to automatically submit evidence when +it is discovered by allowing clients and foreign chains to submit more complex evidence directly. -All concrete evidence types must implement the `Evidence` interface contract. Submitted`Evidence` is first routed through the evidence module's `Router` in which it attempts\ -to find a corresponding registered `Handler` for that specific `Evidence` type.\ -Each `Evidence` type must have a `Handler` registered with the evidence module's\ +All concrete evidence types must implement the `Evidence` interface contract. Submitted +`Evidence` is first routed through the evidence module's `Router` in which it attempts +to find a corresponding registered `Handler` for that specific `Evidence` type. +Each `Evidence` type must have a `Handler` registered with the evidence module's keeper in order for it to be successfully routed and executed. -Each corresponding handler must also fulfill the `Handler` interface contract. The`Handler` for a given `Evidence` type can perform any arbitrary state transitions\ +Each corresponding handler must also fulfill the `Handler` interface contract. The +`Handler` for a given `Evidence` type can perform any arbitrary state transitions such as slashing, jailing, and tombstoning. ## Concepts ### Evidence -Any concrete type of evidence submitted to the `x/evidence` module must fulfill the`Evidence` contract outlined below. Not all concrete types of evidence will fulfill\ -this contract in the same way and some data may be entirely irrelevant to certain\ -types of evidence. An additional `ValidatorEvidence`, which extends `Evidence`,\ +Any concrete type of evidence submitted to the `x/evidence` module must fulfill the +`Evidence` contract outlined below. Not all concrete types of evidence will fulfill +this contract in the same way and some data may be entirely irrelevant to certain +types of evidence. An additional `ValidatorEvidence`, which extends `Evidence`, has also been created to define a contract for evidence against malicious validators. ```go @@ -76,9 +79,10 @@ type ValidatorEvidence interface { ### Registration & Handling -The `x/evidence` module must first know about all types of evidence it is expected\ -to handle. This is accomplished by registering the `Route` method in the `Evidence`\ -contract with what is known as a `Router` (defined below). The `Router` accepts`Evidence` and attempts to find the corresponding `Handler` for the `Evidence`\ +The `x/evidence` module must first know about all types of evidence it is expected +to handle. This is accomplished by registering the `Route` method in the `Evidence` +contract with what is known as a `Router` (defined below). The `Router` accepts +`Evidence` and attempts to find the corresponding `Handler` for the `Evidence` via the `Route` method. ```go @@ -91,11 +95,11 @@ type Router interface { } ``` -The `Handler` (defined below) is responsible for executing the entirety of the\ -business logic for handling `Evidence`. This typically includes validating the\ -evidence, both stateless checks via `ValidateBasic` and stateful checks via any\ -keepers provided to the `Handler`. In addition, the `Handler` may also perform\ -capabilities such as slashing and jailing a validator. All `Evidence` handled\ +The `Handler` (defined below) is responsible for executing the entirety of the +business logic for handling `Evidence`. This typically includes validating the +evidence, both stateless checks via `ValidateBasic` and stateful checks via any +keepers provided to the `Handler`. In addition, the `Handler` may also perform +capabilities such as slashing and jailing a validator. All `Evidence` handled by the `Handler` should be persisted. ```go @@ -106,9 +110,10 @@ by the `Handler` should be persisted. type Handler func(context.Context, Evidence) error ``` + ## State -Currently the `x/evidence` module only stores valid submitted `Evidence` in state.\ +Currently the `x/evidence` module only stores valid submitted `Evidence` in state. The evidence state is also stored and exported in the `x/evidence` module's `GenesisState`. ```protobuf @@ -122,6 +127,7 @@ message GenesisState { All `Evidence` is retrieved and stored via a prefix `KVStore` using prefix `0x00` (`KeyPrefixEvidence`). + ## Messages ### MsgSubmitEvidence @@ -137,10 +143,11 @@ message MsgSubmitEvidence { } ``` -Note, the `Evidence` of a `MsgSubmitEvidence` message must have a corresponding`Handler` registered with the `x/evidence` module's `Router` in order to be processed\ +Note, the `Evidence` of a `MsgSubmitEvidence` message must have a corresponding +`Handler` registered with the `x/evidence` module's `Router` in order to be processed and routed correctly. -Given the `Evidence` is registered with a corresponding `Handler`, it is processed\ +Given the `Evidence` is registered with a corresponding `Handler`, it is processed as follows: ```go @@ -169,10 +176,11 @@ func SubmitEvidence(ctx Context, evidence Evidence) error { } ``` -First, there must not already exist valid submitted `Evidence` of the exact same\ -type. Secondly, the `Evidence` is routed to the `Handler` and executed. Finally,\ +First, there must not already exist valid submitted `Evidence` of the exact same +type. Secondly, the `Evidence` is routed to the `Handler` and executed. Finally, if there is no error in handling the `Evidence`, an event is emitted and it is persisted to state. + ## Events The `x/evidence` module emits the following events: @@ -181,22 +189,25 @@ The `x/evidence` module emits the following events: #### MsgSubmitEvidence -| Type | Attribute Key | Attribute Value | -| ---------------- | -------------- | ---------------- | -| submit\_evidence | evidence\_hash | {evidenceHash} | -| message | module | evidence | -| message | sender | {senderAddress} | -| message | action | submit\_evidence | +| Type | Attribute Key | Attribute Value | +| --------------- | ------------- | --------------- | +| submit_evidence | evidence_hash | {evidenceHash} | +| message | module | evidence | +| message | sender | {senderAddress} | +| message | action | submit_evidence | + ## Parameters The evidence module does not contain any parameters. + ## BeginBlock ### Evidence Handling -CometBFT blocks can include[Evidence](https://github.com/cometbft/cometbft/blob/main/spec/abci/abci%2B%2B_basic_concepts.md#evidence) that indicates if a validator committed malicious behavior. The relevant information is forwarded to the application as ABCI Evidence in `abci.RequestBeginBlock` so that the validator can be punished accordingly. +CometBFT blocks can include +[Evidence](https://github.com/cometbft/cometbft/blob/main/spec/abci/abci%2B%2B_basic_concepts.md#evidence) that indicates if a validator committed malicious behavior. The relevant information is forwarded to the application as ABCI Evidence in `abci.RequestBeginBlock` so that the validator can be punished accordingly. #### Equivocation @@ -207,36 +218,36 @@ The Cosmos SDK handles two types of evidence inside the ABCI `BeginBlock`: The evidence module handles these two evidence types the same way. First, the Cosmos SDK converts the CometBFT concrete evidence type to an SDK `Evidence` interface using `Equivocation` as the concrete type. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/evidence/v1beta1/evidence.proto#L12-L32 ``` For some `Equivocation` submitted in `block` to be valid, it must satisfy: -`Evidence.Timestamp ≥ block.Timestamp - MaxEvidenceAge` +`Evidence.Timestamp >= block.Timestamp - MaxEvidenceAge` Where: * `Evidence.Timestamp` is the timestamp in the block at height `Evidence.Height` * `block.Timestamp` is the current block timestamp. -If valid `Equivocation` evidence is included in a block, the validator's stake is\ -reduced (slashed) by `SlashFractionDoubleSign` as defined by the `x/slashing` module\ -of what their stake was when the infraction occurred, rather than when the evidence was discovered.\ -We want to "follow the stake", i.e., the stake that contributed to the infraction\ +If valid `Equivocation` evidence is included in a block, the validator's stake is +reduced (slashed) by `SlashFractionDoubleSign` as defined by the `x/slashing` module +of what their stake was when the infraction occurred, rather than when the evidence was discovered. +We want to "follow the stake", i.e., the stake that contributed to the infraction should be slashed, even if it has since been redelegated or started unbonding. -In addition, the validator is permanently jailed and tombstoned to make it impossible for that\ +In addition, the validator is permanently jailed and tombstoned to make it impossible for that validator to ever re-enter the validator set. The `Equivocation` evidence is handled as follows: -```go +```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/evidence/keeper/infraction.go#L26-L140 ``` -**Note:** The slashing, jailing, and tombstoning calls are delegated through the `x/slashing` module\ -that emits informative events and finally delegates calls to the `x/staking` module. See documentation\ +**Note:** The slashing, jailing, and tombstoning calls are delegated through the `x/slashing` module +that emits informative events and finally delegates calls to the `x/staking` module. See documentation on slashing and jailing in [State Transitions](../staking/#state-transitions). ## Client diff --git a/.gitbook/developers-native/core/feegrant.mdx b/.gitbook/developers-native/core/feegrant/index.md similarity index 99% rename from .gitbook/developers-native/core/feegrant.mdx rename to .gitbook/developers-native/core/feegrant/index.md index 0752444..26bc7a7 100644 --- a/.gitbook/developers-native/core/feegrant.mdx +++ b/.gitbook/developers-native/core/feegrant/index.md @@ -124,7 +124,7 @@ Example cmd: ### Granted Fee Deductions -Fees are deducted from grants in the `x/auth` ante handler. To learn more about how ante handlers work, read the [Auth Module AnteHandlers Guide](../auth/README.md#antehandlers). +Fees are deducted from grants in the `x/auth` ante handler. To learn more about how ante handlers work, read the [Auth Module AnteHandlers Guide](../auth/#antehandlers). ### Gas diff --git a/.gitbook/developers-native/core/genutil.mdx b/.gitbook/developers-native/core/genutil/index.md similarity index 100% rename from .gitbook/developers-native/core/genutil.mdx rename to .gitbook/developers-native/core/genutil/index.md diff --git a/.gitbook/developers-native/core/gov/index.md b/.gitbook/developers-native/core/gov/index.md new file mode 100644 index 0000000..9d8c309 --- /dev/null +++ b/.gitbook/developers-native/core/gov/index.md @@ -0,0 +1,2547 @@ +--- +sidebar_position: 1 +--- + +# `x/gov` + +## Abstract + +This paper specifies the Governance module of the Cosmos SDK, which was first +described in the [Cosmos Whitepaper](https://cosmos.network/about/whitepaper) in +June 2016. + +The module enables Cosmos SDK based blockchain to support an on-chain governance +system. In this system, holders of the native staking token of the chain can vote +on proposals on a 1 token 1 vote basis. Next is a list of features the module +currently supports: + +* **Proposal submission:** Users can submit proposals with a deposit. Once the +minimum deposit is reached, the proposal enters voting period. The minimum deposit can be reached by collecting deposits from different users (including proposer) within deposit period. +* **Vote:** Participants can vote on proposals that reached MinDeposit and entered voting period. +* **Inheritance and penalties:** Delegators inherit their validator's vote if +they don't vote themselves. +* **Claiming deposit:** Users that deposited on proposals can recover their +deposits if the proposal was accepted or rejected. If the proposal was vetoed, or never entered voting period (minimum deposit not reached within deposit period), the deposit is burned. + +This module is in use on the Cosmos Hub (a.k.a [gaia](https://github.com/cosmos/gaia)). +Features that may be added in the future are described in [Future Improvements](#future-improvements). + +## Contents + +The following specification uses *ATOM* as the native staking token. The module +can be adapted to any Proof-Of-Stake blockchain by replacing *ATOM* with the native +staking token of the chain. + +* [Concepts](#concepts) + * [Proposal submission](#proposal-submission) + * [Deposit](#deposit) + * [Vote](#vote) + * [Software Upgrade](#software-upgrade) +* [State](#state) + * [Proposals](#proposals) + * [Parameters and base types](#parameters-and-base-types) + * [Deposit](#deposit-1) + * [ValidatorGovInfo](#validatorgovinfo) + * [Stores](#stores) + * [Proposal Processing Queue](#proposal-processing-queue) + * [Legacy Proposal](#legacy-proposal) +* [Messages](#messages) + * [Proposal Submission](#proposal-submission-1) + * [Deposit](#deposit-2) + * [Vote](#vote-1) +* [Events](#events) + * [EndBlocker](#endblocker) + * [Handlers](#handlers) +* [Parameters](#parameters) +* [Client](#client) + * [CLI](#cli) + * [gRPC](#grpc) + * [REST](#rest) +* [Metadata](#metadata) + * [Proposal](#proposal-3) + * [Vote](#vote-5) +* [Future Improvements](#future-improvements) + +## Concepts + +*Disclaimer: This is work in progress. Mechanisms are susceptible to change.* + +The governance process is divided in a few steps that are outlined below: + +* **Proposal submission:** Proposal is submitted to the blockchain with a + deposit. +* **Vote:** Once deposit reaches a certain value (`MinDeposit`), proposal is + confirmed and vote opens. Bonded Atom holders can then send `TxGovVote` + transactions to vote on the proposal. +* **Execution** After a period of time, the votes are tallied and depending + on the result, the messages in the proposal will be executed. + +### Proposal submission + +#### Right to submit a proposal + +Every account can submit proposals by sending a `MsgSubmitProposal` transaction. +Once a proposal is submitted, it is identified by its unique `proposalID`. + +#### Proposal Messages + +A proposal includes an array of `sdk.Msg`s which are executed automatically if the +proposal passes. The messages are executed by the governance `ModuleAccount` itself. Modules +such as `x/upgrade`, that want to allow certain messages to be executed by governance +only should add a whitelist within the respective msg server, granting the governance +module the right to execute the message once a quorum has been reached. The governance +module uses the `MsgServiceRouter` to check that these messages are correctly constructed +and have a respective path to execute on but do not perform a full validity check. + +### Deposit + +To prevent spam, proposals must be submitted with a deposit in the coins defined by +the `MinDeposit` param. + +When a proposal is submitted, it has to be accompanied with a deposit that must be +strictly positive, but can be inferior to `MinDeposit`. The submitter doesn't need +to pay for the entire deposit on their own. The newly created proposal is stored in +an *inactive proposal queue* and stays there until its deposit passes the `MinDeposit`. +Other token holders can increase the proposal's deposit by sending a `Deposit` +transaction. If a proposal doesn't pass the `MinDeposit` before the deposit end time +(the time when deposits are no longer accepted), the proposal will be destroyed: the +proposal will be removed from state and the deposit will be burned (see x/gov `EndBlocker`). +When a proposal deposit passes the `MinDeposit` threshold (even during the proposal +submission) before the deposit end time, the proposal will be moved into the +*active proposal queue* and the voting period will begin. + +The deposit is kept in escrow and held by the governance `ModuleAccount` until the +proposal is finalized (passed or rejected). + +#### Deposit refund and burn + +When a proposal is finalized, the coins from the deposit are either refunded or burned +according to the final tally of the proposal: + +* If the proposal is approved or rejected but *not* vetoed, each deposit will be + automatically refunded to its respective depositor (transferred from the governance + `ModuleAccount`). +* When the proposal is vetoed with greater than 1/3, deposits will be burned from the + governance `ModuleAccount` and the proposal information along with its deposit + information will be removed from state. +* All refunded or burned deposits are removed from the state. Events are issued when + burning or refunding a deposit. + +### Vote + +#### Participants + +*Participants* are users that have the right to vote on proposals. On the +Cosmos Hub, participants are bonded Atom holders. Unbonded Atom holders and +other users do not get the right to participate in governance. However, they +can submit and deposit on proposals. + +Note that when *participants* have bonded and unbonded Atoms, their voting power is calculated from their bonded Atom holdings only. + +#### Voting period + +Once a proposal reaches `MinDeposit`, it immediately enters `Voting period`. We +define `Voting period` as the interval between the moment the vote opens and +the moment the vote closes. The initial value of `Voting period` is 2 weeks. + +#### Option set + +The option set of a proposal refers to the set of choices a participant can +choose from when casting its vote. + +The initial option set includes the following options: + +* `Yes` +* `No` +* `NoWithVeto` +* `Abstain` + +`NoWithVeto` counts as `No` but also adds a `Veto` vote. `Abstain` option +allows voters to signal that they do not intend to vote in favor or against the +proposal but accept the result of the vote. + +*Note: from the UI, for urgent proposals we should maybe add a ‘Not Urgent’ option that casts a `NoWithVeto` vote.* + +#### Weighted Votes + +[ADR-037](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-037-gov-split-vote.md) introduces the weighted vote feature which allows a staker to split their votes into several voting options. For example, it could use 70% of its voting power to vote Yes and 30% of its voting power to vote No. + +Often times the entity owning that address might not be a single individual. For example, a company might have different stakeholders who want to vote differently, and so it makes sense to allow them to split their voting power. Currently, it is not possible for them to do "passthrough voting" and giving their users voting rights over their tokens. However, with this system, exchanges can poll their users for voting preferences, and then vote on-chain proportionally to the results of the poll. + +To represent weighted vote on chain, we use the following Protobuf message. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1beta1/gov.proto#L34-L47 +``` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1beta1/gov.proto#L181-L201 +``` + +For a weighted vote to be valid, the `options` field must not contain duplicate vote options, and the sum of weights of all options must be equal to 1. + +### Quorum + +Quorum is defined as the minimum percentage of voting power that needs to be +cast on a proposal for the result to be valid. + +### Expedited Proposals + +A proposal can be expedited, making the proposal use shorter voting duration and a higher tally threshold by its default. If an expedited proposal fails to meet the threshold within the scope of shorter voting duration, the expedited proposal is then converted to a regular proposal and restarts voting under regular voting conditions. + +#### Threshold + +Threshold is defined as the minimum proportion of `Yes` votes (excluding +`Abstain` votes) for the proposal to be accepted. + +Initially, the threshold is set at 50% of `Yes` votes, excluding `Abstain` +votes. A possibility to veto exists if more than 1/3rd of all votes are +`NoWithVeto` votes. Note, both of these values are derived from the `TallyParams` +on-chain parameter, which is modifiable by governance. +This means that proposals are accepted iff: + +* There exist bonded tokens. +* Quorum has been achieved. +* The proportion of `Abstain` votes is inferior to 1/1. +* The proportion of `NoWithVeto` votes is inferior to 1/3, including + `Abstain` votes. +* The proportion of `Yes` votes, excluding `Abstain` votes, at the end of + the voting period is superior to 1/2. + +For expedited proposals, by default, the threshold is higher than with a *normal proposal*, namely, 66.7%. + +#### Inheritance + +If a delegator does not vote, it will inherit its validator vote. + +* If the delegator votes before its validator, it will not inherit from the + validator's vote. +* If the delegator votes after its validator, it will override its validator + vote with its own. If the proposal is urgent, it is possible + that the vote will close before delegators have a chance to react and + override their validator's vote. This is not a problem, as proposals require more than 2/3rd of the total voting power to pass, when tallied at the end of the voting period. Because as little as 1/3 + 1 validation power could collude to censor transactions, non-collusion is already assumed for ranges exceeding this threshold. + +#### Validator’s punishment for non-voting + +At present, validators are not punished for failing to vote. + +#### Governance address + +Later, we may add permissioned keys that could only sign txs from certain modules. For the MVP, the `Governance address` will be the main validator address generated at account creation. This address corresponds to a different PrivKey than the CometBFT PrivKey which is responsible for signing consensus messages. Validators thus do not have to sign governance transactions with the sensitive CometBFT PrivKey. + +#### Burnable Params + +There are three parameters that define if the deposit of a proposal should be burned or returned to the depositors. + +* `BurnVoteVeto` burns the proposal deposit if the proposal gets vetoed. +* `BurnVoteQuorum` burns the proposal deposit if the proposal deposit if the vote does not reach quorum. +* `BurnProposalDepositPrevote` burns the proposal deposit if it does not enter the voting phase. + +> Note: These parameters are modifiable via governance. + +## State + +### Constitution + +`Constitution` is found in the genesis state. It is a string field intended to be used to descibe the purpose of a particular blockchain, and its expected norms. A few examples of how the constitution field can be used: + +* define the purpose of the chain, laying a foundation for its future development +* set expectations for delegators +* set expectations for validators +* define the chain's relationship to "meatspace" entities, like a foundation or corporation + +Since this is more of a social feature than a technical feature, we'll now get into some items that may have been useful to have in a genesis constitution: + +* What limitations on governance exist, if any? + * is it okay for the community to slash the wallet of a whale that they no longer feel that they want around? (viz: Juno Proposal 4 and 16) + * can governance "socially slash" a validator who is using unapproved MEV? (viz: commonwealth.im/osmosis) + * In the event of an economic emergency, what should validators do? + * Terra crash of May, 2022, saw validators choose to run a new binary with code that had not been approved by governance, because the governance token had been inflated to nothing. +* What is the purpose of the chain, specifically? + * best example of this is the Cosmos hub, where different founding groups, have different interpertations of the purpose of the network. + +This genesis entry, "constitution" hasn't been designed for existing chains, who should likely just ratify a constitution using their governance system. Instead, this is for new chains. It will allow for validators to have a much clearer idea of purpose and the expecations placed on them while operating thier nodes. Likewise, for community members, the constitution will give them some idea of what to expect from both the "chain team" and the validators, respectively. + +This constitution is designed to be immutable, and placed only in genesis, though that could change over time by a pull request to the cosmos-sdk that allows for the constitution to be changed by governance. Communities whishing to make amendments to their original constitution should use the governance mechanism and a "signaling proposal" to do exactly that. + +**Ideal use scenario for a cosmos chain constitution** + +As a chain developer, you decide that you'd like to provide clarity to your key user groups: + +* validators +* token holders +* developers (yourself) + +You use the constitution to immutably store some Markdown in genesis, so that when difficult questions come up, the constutituon can provide guidance to the community. + +### Proposals + +`Proposal` objects are used to tally votes and generally track the proposal's state. +They contain an array of arbitrary `sdk.Msg`'s which the governance module will attempt +to resolve and then execute if the proposal passes. `Proposal`'s are identified by a +unique id and contains a series of timestamps: `submit_time`, `deposit_end_time`, +`voting_start_time`, `voting_end_time` which track the lifecycle of a proposal + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1/gov.proto#L51-L99 +``` + +A proposal will generally require more than just a set of messages to explain its +purpose but need some greater justification and allow a means for interested participants +to discuss and debate the proposal. +In most cases, **it is encouraged to have an off-chain system that supports the on-chain governance process**. +To accommodate for this, a proposal contains a special **`metadata`** field, a string, +which can be used to add context to the proposal. The `metadata` field allows custom use for networks, +however, it is expected that the field contains a URL or some form of CID using a system such as +[IPFS](https://docs.ipfs.io/concepts/content-addressing/). To support the case of +interoperability across networks, the SDK recommends that the `metadata` represents +the following `JSON` template: + +```json +{ + "title": "...", + "description": "...", + "forum": "...", // a link to the discussion platform (i.e. Discord) + "other": "..." // any extra data that doesn't correspond to the other fields +} +``` + +This makes it far easier for clients to support multiple networks. + +The metadata has a maximum length that is chosen by the app developer, and +passed into the gov keeper as a config. The default maximum length in the SDK is 255 characters. + +#### Writing a module that uses governance + +There are many aspects of a chain, or of the individual modules that you may want to +use governance to perform such as changing various parameters. This is very simple +to do. First, write out your message types and `MsgServer` implementation. Add an +`authority` field to the keeper which will be populated in the constructor with the +governance module account: `govKeeper.GetGovernanceAccount().GetAddress()`. Then for +the methods in the `msg_server.go`, perform a check on the message that the signer +matches `authority`. This will prevent any user from executing that message. + +### Parameters and base types + +`Parameters` define the rules according to which votes are run. There can only +be one active parameter set at any given time. If governance wants to change a +parameter set, either to modify a value or add/remove a parameter field, a new +parameter set has to be created and the previous one rendered inactive. + +#### DepositParams + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1/gov.proto#L152-L162 +``` + +#### VotingParams + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1/gov.proto#L164-L168 +``` + +#### TallyParams + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1/gov.proto#L170-L182 +``` + +Parameters are stored in a global `GlobalParams` KVStore. + +Additionally, we introduce some basic types: + +```go +type Vote byte + +const ( + VoteYes = 0x1 + VoteNo = 0x2 + VoteNoWithVeto = 0x3 + VoteAbstain = 0x4 +) + +type ProposalType string + +const ( + ProposalTypePlainText = "Text" + ProposalTypeSoftwareUpgrade = "SoftwareUpgrade" +) + +type ProposalStatus byte + + +const ( + StatusNil ProposalStatus = 0x00 + StatusDepositPeriod ProposalStatus = 0x01 // Proposal is submitted. Participants can deposit on it but not vote + StatusVotingPeriod ProposalStatus = 0x02 // MinDeposit is reached, participants can vote + StatusPassed ProposalStatus = 0x03 // Proposal passed and successfully executed + StatusRejected ProposalStatus = 0x04 // Proposal has been rejected + StatusFailed ProposalStatus = 0x05 // Proposal passed but failed execution +) +``` + +### Deposit + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1/gov.proto#L38-L49 +``` + +### ValidatorGovInfo + +This type is used in a temp map when tallying + +```go + type ValidatorGovInfo struct { + Minus sdk.Dec + Vote Vote + } +``` + +## Stores + +:::note +Stores are KVStores in the multi-store. The key to find the store is the first parameter in the list +::: + +We will use one KVStore `Governance` to store four mappings: + +* A mapping from `proposalID|'proposal'` to `Proposal`. +* A mapping from `proposalID|'addresses'|address` to `Vote`. This mapping allows + us to query all addresses that voted on the proposal along with their vote by + doing a range query on `proposalID:addresses`. +* A mapping from `ParamsKey|'Params'` to `Params`. This map allows to query all + x/gov params. +* A mapping from `VotingPeriodProposalKeyPrefix|proposalID` to a single byte. This allows + us to know if a proposal is in the voting period or not with very low gas cost. + +For pseudocode purposes, here are the two function we will use to read or write in stores: + +* `load(StoreKey, Key)`: Retrieve item stored at key `Key` in store found at key `StoreKey` in the multistore +* `store(StoreKey, Key, value)`: Write value `Value` at key `Key` in store found at key `StoreKey` in the multistore + +### Proposal Processing Queue + +**Store:** + +* `ProposalProcessingQueue`: A queue `queue[proposalID]` containing all the + `ProposalIDs` of proposals that reached `MinDeposit`. During each `EndBlock`, + all the proposals that have reached the end of their voting period are processed. + To process a finished proposal, the application tallies the votes, computes the + votes of each validator and checks if every validator in the validator set has + voted. If the proposal is accepted, deposits are refunded. Finally, the proposal + content `Handler` is executed. + +And the pseudocode for the `ProposalProcessingQueue`: + +```go + in EndBlock do + + for finishedProposalID in GetAllFinishedProposalIDs(block.Time) + proposal = load(Governance, ) // proposal is a const key + + validators = Keeper.getAllValidators() + tmpValMap := map(sdk.AccAddress)ValidatorGovInfo + + // Initiate mapping at 0. This is the amount of shares of the validator's vote that will be overridden by their delegator's votes + for each validator in validators + tmpValMap(validator.OperatorAddr).Minus = 0 + + // Tally + voterIterator = rangeQuery(Governance, ) //return all the addresses that voted on the proposal + for each (voterAddress, vote) in voterIterator + delegations = stakingKeeper.getDelegations(voterAddress) // get all delegations for current voter + + for each delegation in delegations + // make sure delegation.Shares does NOT include shares being unbonded + tmpValMap(delegation.ValidatorAddr).Minus += delegation.Shares + proposal.updateTally(vote, delegation.Shares) + + _, isVal = stakingKeeper.getValidator(voterAddress) + if (isVal) + tmpValMap(voterAddress).Vote = vote + + tallyingParam = load(GlobalParams, 'TallyingParam') + + // Update tally if validator voted + for each validator in validators + if tmpValMap(validator).HasVoted + proposal.updateTally(tmpValMap(validator).Vote, (validator.TotalShares - tmpValMap(validator).Minus)) + + + + // Check if proposal is accepted or rejected + totalNonAbstain := proposal.YesVotes + proposal.NoVotes + proposal.NoWithVetoVotes + if (proposal.Votes.YesVotes/totalNonAbstain > tallyingParam.Threshold AND proposal.Votes.NoWithVetoVotes/totalNonAbstain < tallyingParam.Veto) + // proposal was accepted at the end of the voting period + // refund deposits (non-voters already punished) + for each (amount, depositor) in proposal.Deposits + depositor.AtomBalance += amount + + stateWriter, err := proposal.Handler() + if err != nil + // proposal passed but failed during state execution + proposal.CurrentStatus = ProposalStatusFailed + else + // proposal pass and state is persisted + proposal.CurrentStatus = ProposalStatusAccepted + stateWriter.save() + else + // proposal was rejected + proposal.CurrentStatus = ProposalStatusRejected + + store(Governance, , proposal) +``` + +### Legacy Proposal + +:::warning +Legacy proposals are deprecated. Use the new proposal flow by granting the governance module the right to execute the message. +::: + +A legacy proposal is the old implementation of governance proposal. +Contrary to proposal that can contain any messages, a legacy proposal allows to submit a set of pre-defined proposals. +These proposals are defined by their types and handled by handlers that are registered in the gov v1beta1 router. + +More information on how to submit proposals in the [client section](#client). + +## Messages + +### Proposal Submission + +Proposals can be submitted by any account via a `MsgSubmitProposal` transaction. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1/tx.proto#L42-L69 +``` + +All `sdk.Msgs` passed into the `messages` field of a `MsgSubmitProposal` message +must be registered in the app's `MsgServiceRouter`. Each of these messages must +have one signer, namely the gov module account. And finally, the metadata length +must not be larger than the `maxMetadataLen` config passed into the gov keeper. +The `initialDeposit` must be strictly positive and conform to the accepted denom of the `MinDeposit` param. + +**State modifications:** + +* Generate new `proposalID` +* Create new `Proposal` +* Initialise `Proposal`'s attributes +* Decrease balance of sender by `InitialDeposit` +* If `MinDeposit` is reached: + * Push `proposalID` in `ProposalProcessingQueue` +* Transfer `InitialDeposit` from the `Proposer` to the governance `ModuleAccount` + +### Deposit + +Once a proposal is submitted, if `Proposal.TotalDeposit < ActiveParam.MinDeposit`, Atom holders can send +`MsgDeposit` transactions to increase the proposal's deposit. + +A deposit is accepted iff: + +* The proposal exists +* The proposal is not in the voting period +* The deposited coins are conform to the accepted denom from the `MinDeposit` param + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1/tx.proto#L134-L147 +``` + +**State modifications:** + +* Decrease balance of sender by `deposit` +* Add `deposit` of sender in `proposal.Deposits` +* Increase `proposal.TotalDeposit` by sender's `deposit` +* If `MinDeposit` is reached: + * Push `proposalID` in `ProposalProcessingQueueEnd` +* Transfer `Deposit` from the `proposer` to the governance `ModuleAccount` + +### Vote + +Once `ActiveParam.MinDeposit` is reached, voting period starts. From there, +bonded Atom holders are able to send `MsgVote` transactions to cast their +vote on the proposal. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1/tx.proto#L92-L108 +``` + +**State modifications:** + +* Record `Vote` of sender + +:::note +Gas cost for this message has to take into account the future tallying of the vote in EndBlocker. +::: + +## Events + +The governance module emits the following events: + +### EndBlocker + +| Type | Attribute Key | Attribute Value | +|-------------------|-----------------|------------------| +| inactive_proposal | proposal_id | `{proposalID}` | +| inactive_proposal | proposal_result | `{proposalResult}` | +| active_proposal | proposal_id | `{proposalID}` | +| active_proposal | proposal_result | `{proposalResult}` | + +### Handlers + +#### MsgSubmitProposal + +| Type | Attribute Key | Attribute Value | +|---------------------|---------------------|-----------------| +| submit_proposal | proposal_id | `{proposalID}` | +| submit_proposal [0] | voting_period_start | `{proposalID}` | +| proposal_deposit | amount | `{depositAmount}` | +| proposal_deposit | proposal_id | `{proposalID}` | +| message | module | `governance` | +| message | action | `submit_proposal` | +| message | sender | `{senderAddress}` | + +* [0] Event only emitted if the voting period starts during the submission. + +#### MsgVote + +| Type | Attribute Key | Attribute Value | +|---------------|---------------|-----------------| +| proposal_vote | option | `{voteOption}` | +| proposal_vote | proposal_id | `{proposalID}` | +| message | module | `governance` | +| message | action | `vote` | +| message | sender | `{senderAddress}` | + +#### MsgVoteWeighted + +| Type | Attribute Key | Attribute Value | +|---------------|---------------|-----------------------| +| proposal_vote | option | `{weightedVoteOptions}` | +| proposal_vote | proposal_id | `{proposalID}` | +| message | module | `governance` | +| message | action | `vote` | +| message | sender | `{senderAddress}` | + +#### MsgDeposit + +| Type | Attribute Key | Attribute Value | +|----------------------|---------------------|-----------------| +| proposal_deposit | amount | `{depositAmount}` | +| proposal_deposit | proposal_id | `{proposalID}` | +| proposal_deposit [0] | voting_period_start | `{proposalID}` | +| message | module | `governance` | +| message | action | `deposit` | +| message | sender | `{senderAddress}` | + +* [0] Event only emitted if the voting period starts during the submission. + +## Parameters + +The governance module contains the following parameters: + +| Key | Type | Example | +|-------------------------------|------------------|-----------------------------------------| +| min_deposit | array (coins) | `[{"denom":"uatom","amount":"10000000"}]` | +| max_deposit_period | string (time ns) | `"172800000000000"` (17280s) | +| voting_period | string (time ns) | `"172800000000000"` (17280s) | +| quorum | string (dec) | `"0.334000000000000000"` | +| threshold | string (dec) | `"0.500000000000000000"` | +| veto | string (dec) | `"0.334000000000000000"` | +| expedited_threshold | string (time ns) | `"0.667000000000000000"` | +| expedited_voting_period | string (time ns) | `"86400000000000"` (8600s) | +| expedited_min_deposit | array (coins) | `[{"denom":"uatom","amount":"50000000"}]` | +| burn_proposal_deposit_prevote | bool | `false` | +| burn_vote_quorum | bool | `false` | +| burn_vote_veto | bool | `true` | +| min_initial_deposit_ratio | string | `"0.1"` | + + +**NOTE**: The governance module contains parameters that are objects unlike other +modules. If only a subset of parameters are desired to be changed, only they need +to be included and not the entire parameter object structure. + +## Client + +### CLI + +A user can query and interact with the `gov` module using the CLI. + +#### Query + +The `query` commands allow users to query `gov` state. + +```bash +simd query gov --help +``` + +##### deposit + +The `deposit` command allows users to query a deposit for a given proposal from a given depositor. + +```bash +simd query gov deposit [proposal-id] [depositer-addr] [flags] +``` + +Example: + +```bash +simd query gov deposit 1 cosmos1.. +``` + +Example Output: + +```bash +amount: +- amount: "100" + denom: stake +depositor: cosmos1.. +proposal_id: "1" +``` + +##### deposits + +The `deposits` command allows users to query all deposits for a given proposal. + +```bash +simd query gov deposits [proposal-id] [flags] +``` + +Example: + +```bash +simd query gov deposits 1 +``` + +Example Output: + +```bash +deposits: +- amount: + - amount: "100" + denom: stake + depositor: cosmos1.. + proposal_id: "1" +pagination: + next_key: null + total: "0" +``` + +##### param + +The `param` command allows users to query a given parameter for the `gov` module. + +```bash +simd query gov param [param-type] [flags] +``` + +Example: + +```bash +simd query gov param voting +``` + +Example Output: + +```bash +voting_period: "172800000000000" +``` + +##### params + +The `params` command allows users to query all parameters for the `gov` module. + +```bash +simd query gov params [flags] +``` + +Example: + +```bash +simd query gov params +``` + +Example Output: + +```bash +deposit_params: + max_deposit_period: 172800s + min_deposit: + - amount: "10000000" + denom: stake +params: + expedited_min_deposit: + - amount: "50000000" + denom: stake + expedited_threshold: "0.670000000000000000" + expedited_voting_period: 86400s + max_deposit_period: 172800s + min_deposit: + - amount: "10000000" + denom: stake + min_initial_deposit_ratio: "0.000000000000000000" + proposal_cancel_burn_rate: "0.500000000000000000" + quorum: "0.334000000000000000" + threshold: "0.500000000000000000" + veto_threshold: "0.334000000000000000" + voting_period: 172800s +tally_params: + quorum: "0.334000000000000000" + threshold: "0.500000000000000000" + veto_threshold: "0.334000000000000000" +voting_params: + voting_period: 172800s +``` + +##### proposal + +The `proposal` command allows users to query a given proposal. + +```bash +simd query gov proposal [proposal-id] [flags] +``` + +Example: + +```bash +simd query gov proposal 1 +``` + +Example Output: + +```bash +deposit_end_time: "2022-03-30T11:50:20.819676256Z" +final_tally_result: + abstain_count: "0" + no_count: "0" + no_with_veto_count: "0" + yes_count: "0" +id: "1" +messages: +- '@type': /cosmos.bank.v1beta1.MsgSend + amount: + - amount: "10" + denom: stake + from_address: cosmos1.. + to_address: cosmos1.. +metadata: AQ== +status: PROPOSAL_STATUS_DEPOSIT_PERIOD +submit_time: "2022-03-28T11:50:20.819676256Z" +total_deposit: +- amount: "10" + denom: stake +voting_end_time: null +voting_start_time: null +``` + +##### proposals + +The `proposals` command allows users to query all proposals with optional filters. + +```bash +simd query gov proposals [flags] +``` + +Example: + +```bash +simd query gov proposals +``` + +Example Output: + +```bash +pagination: + next_key: null + total: "0" +proposals: +- deposit_end_time: "2022-03-30T11:50:20.819676256Z" + final_tally_result: + abstain_count: "0" + no_count: "0" + no_with_veto_count: "0" + yes_count: "0" + id: "1" + messages: + - '@type': /cosmos.bank.v1beta1.MsgSend + amount: + - amount: "10" + denom: stake + from_address: cosmos1.. + to_address: cosmos1.. + metadata: AQ== + status: PROPOSAL_STATUS_DEPOSIT_PERIOD + submit_time: "2022-03-28T11:50:20.819676256Z" + total_deposit: + - amount: "10" + denom: stake + voting_end_time: null + voting_start_time: null +- deposit_end_time: "2022-03-30T14:02:41.165025015Z" + final_tally_result: + abstain_count: "0" + no_count: "0" + no_with_veto_count: "0" + yes_count: "0" + id: "2" + messages: + - '@type': /cosmos.bank.v1beta1.MsgSend + amount: + - amount: "10" + denom: stake + from_address: cosmos1.. + to_address: cosmos1.. + metadata: AQ== + status: PROPOSAL_STATUS_DEPOSIT_PERIOD + submit_time: "2022-03-28T14:02:41.165025015Z" + total_deposit: + - amount: "10" + denom: stake + voting_end_time: null + voting_start_time: null +``` + +##### proposer + +The `proposer` command allows users to query the proposer for a given proposal. + +```bash +simd query gov proposer [proposal-id] [flags] +``` + +Example: + +```bash +simd query gov proposer 1 +``` + +Example Output: + +```bash +proposal_id: "1" +proposer: cosmos1.. +``` + +##### tally + +The `tally` command allows users to query the tally of a given proposal vote. + +```bash +simd query gov tally [proposal-id] [flags] +``` + +Example: + +```bash +simd query gov tally 1 +``` + +Example Output: + +```bash +abstain: "0" +"no": "0" +no_with_veto: "0" +"yes": "1" +``` + +##### vote + +The `vote` command allows users to query a vote for a given proposal. + +```bash +simd query gov vote [proposal-id] [voter-addr] [flags] +``` + +Example: + +```bash +simd query gov vote 1 cosmos1.. +``` + +Example Output: + +```bash +option: VOTE_OPTION_YES +options: +- option: VOTE_OPTION_YES + weight: "1.000000000000000000" +proposal_id: "1" +voter: cosmos1.. +``` + +##### votes + +The `votes` command allows users to query all votes for a given proposal. + +```bash +simd query gov votes [proposal-id] [flags] +``` + +Example: + +```bash +simd query gov votes 1 +``` + +Example Output: + +```bash +pagination: + next_key: null + total: "0" +votes: +- option: VOTE_OPTION_YES + options: + - option: VOTE_OPTION_YES + weight: "1.000000000000000000" + proposal_id: "1" + voter: cosmos1.. +``` + +#### Transactions + +The `tx` commands allow users to interact with the `gov` module. + +```bash +simd tx gov --help +``` + +##### deposit + +The `deposit` command allows users to deposit tokens for a given proposal. + +```bash +simd tx gov deposit [proposal-id] [deposit] [flags] +``` + +Example: + +```bash +simd tx gov deposit 1 10000000stake --from cosmos1.. +``` + +##### draft-proposal + +The `draft-proposal` command allows users to draft any type of proposal. +The command returns a `draft_proposal.json`, to be used by `submit-proposal` after being completed. +The `draft_metadata.json` is meant to be uploaded to [IPFS](#metadata). + +```bash +simd tx gov draft-proposal +``` + +##### submit-proposal + +The `submit-proposal` command allows users to submit a governance proposal along with some messages and metadata. +Messages, metadata and deposit are defined in a JSON file. + +```bash +simd tx gov submit-proposal [path-to-proposal-json] [flags] +``` + +Example: + +```bash +simd tx gov submit-proposal /path/to/proposal.json --from cosmos1.. +``` + +where `proposal.json` contains: + +```json +{ + "messages": [ + { + "@type": "/cosmos.bank.v1beta1.MsgSend", + "from_address": "cosmos1...", // The gov module module address + "to_address": "cosmos1...", + "amount":[{"denom": "stake","amount": "10"}] + } + ], + "metadata": "AQ==", + "deposit": "10stake", + "title": "Proposal Title", + "summary": "Proposal Summary" +} +``` + +:::note +By default the metadata, summary and title are both limited by 255 characters, this can be overridden by the application developer. +::: + +:::tip +When metadata is not specified, the title is limited to 255 characters and the summary 40x the title length. +::: + +##### submit-legacy-proposal + +The `submit-legacy-proposal` command allows users to submit a governance legacy proposal along with an initial deposit. + +```bash +simd tx gov submit-legacy-proposal [command] [flags] +``` + +Example: + +```bash +simd tx gov submit-legacy-proposal --title="Test Proposal" --description="testing" --type="Text" --deposit="100000000stake" --from cosmos1.. +``` + +Example (`param-change`): + +```bash +simd tx gov submit-legacy-proposal param-change proposal.json --from cosmos1.. +``` + +```json +{ + "title": "Test Proposal", + "description": "testing, testing, 1, 2, 3", + "changes": [ + { + "subspace": "staking", + "key": "MaxValidators", + "value": 100 + } + ], + "deposit": "10000000stake" +} +``` + +#### cancel-proposal + +Once proposal is canceled, from the deposits of proposal `deposits * proposal_cancel_ratio` will be burned or sent to `ProposalCancelDest` address , if `ProposalCancelDest` is empty then deposits will be burned. The `remaining deposits` will be sent to depositers. + +```bash +simd tx gov cancel-proposal [proposal-id] [flags] +``` + +Example: + +```bash +simd tx gov cancel-proposal 1 --from cosmos1... +``` + +##### vote + +The `vote` command allows users to submit a vote for a given governance proposal. + +```bash +simd tx gov vote [command] [flags] +``` + +Example: + +```bash +simd tx gov vote 1 yes --from cosmos1.. +``` + +##### weighted-vote + +The `weighted-vote` command allows users to submit a weighted vote for a given governance proposal. + +```bash +simd tx gov weighted-vote [proposal-id] [weighted-options] [flags] +``` + +Example: + +```bash +simd tx gov weighted-vote 1 yes=0.5,no=0.5 --from cosmos1.. +``` + +### gRPC + +A user can query the `gov` module using gRPC endpoints. + +#### Proposal + +The `Proposal` endpoint allows users to query a given proposal. + +Using legacy v1beta1: + +```bash +cosmos.gov.v1beta1.Query/Proposal +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1"}' \ + localhost:9090 \ + cosmos.gov.v1beta1.Query/Proposal +``` + +Example Output: + +```bash +{ + "proposal": { + "proposalId": "1", + "content": {"@type":"/cosmos.gov.v1beta1.TextProposal","description":"testing, testing, 1, 2, 3","title":"Test Proposal"}, + "status": "PROPOSAL_STATUS_VOTING_PERIOD", + "finalTallyResult": { + "yes": "0", + "abstain": "0", + "no": "0", + "noWithVeto": "0" + }, + "submitTime": "2021-09-16T19:40:08.712440474Z", + "depositEndTime": "2021-09-18T19:40:08.712440474Z", + "totalDeposit": [ + { + "denom": "stake", + "amount": "10000000" + } + ], + "votingStartTime": "2021-09-16T19:40:08.712440474Z", + "votingEndTime": "2021-09-18T19:40:08.712440474Z", + "title": "Test Proposal", + "summary": "testing, testing, 1, 2, 3" + } +} +``` + +Using v1: + +```bash +cosmos.gov.v1.Query/Proposal +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1"}' \ + localhost:9090 \ + cosmos.gov.v1.Query/Proposal +``` + +Example Output: + +```bash +{ + "proposal": { + "id": "1", + "messages": [ + {"@type":"/cosmos.bank.v1beta1.MsgSend","amount":[{"denom":"stake","amount":"10"}],"fromAddress":"cosmos1..","toAddress":"cosmos1.."} + ], + "status": "PROPOSAL_STATUS_VOTING_PERIOD", + "finalTallyResult": { + "yesCount": "0", + "abstainCount": "0", + "noCount": "0", + "noWithVetoCount": "0" + }, + "submitTime": "2022-03-28T11:50:20.819676256Z", + "depositEndTime": "2022-03-30T11:50:20.819676256Z", + "totalDeposit": [ + { + "denom": "stake", + "amount": "10000000" + } + ], + "votingStartTime": "2022-03-28T14:25:26.644857113Z", + "votingEndTime": "2022-03-30T14:25:26.644857113Z", + "metadata": "AQ==", + "title": "Test Proposal", + "summary": "testing, testing, 1, 2, 3" + } +} +``` + +#### Proposals + +The `Proposals` endpoint allows users to query all proposals with optional filters. + +Using legacy v1beta1: + +```bash +cosmos.gov.v1beta1.Query/Proposals +``` + +Example: + +```bash +grpcurl -plaintext \ + localhost:9090 \ + cosmos.gov.v1beta1.Query/Proposals +``` + +Example Output: + +```bash +{ + "proposals": [ + { + "proposalId": "1", + "status": "PROPOSAL_STATUS_VOTING_PERIOD", + "finalTallyResult": { + "yes": "0", + "abstain": "0", + "no": "0", + "noWithVeto": "0" + }, + "submitTime": "2022-03-28T11:50:20.819676256Z", + "depositEndTime": "2022-03-30T11:50:20.819676256Z", + "totalDeposit": [ + { + "denom": "stake", + "amount": "10000000010" + } + ], + "votingStartTime": "2022-03-28T14:25:26.644857113Z", + "votingEndTime": "2022-03-30T14:25:26.644857113Z" + }, + { + "proposalId": "2", + "status": "PROPOSAL_STATUS_DEPOSIT_PERIOD", + "finalTallyResult": { + "yes": "0", + "abstain": "0", + "no": "0", + "noWithVeto": "0" + }, + "submitTime": "2022-03-28T14:02:41.165025015Z", + "depositEndTime": "2022-03-30T14:02:41.165025015Z", + "totalDeposit": [ + { + "denom": "stake", + "amount": "10" + } + ], + "votingStartTime": "0001-01-01T00:00:00Z", + "votingEndTime": "0001-01-01T00:00:00Z" + } + ], + "pagination": { + "total": "2" + } +} + +``` + +Using v1: + +```bash +cosmos.gov.v1.Query/Proposals +``` + +Example: + +```bash +grpcurl -plaintext \ + localhost:9090 \ + cosmos.gov.v1.Query/Proposals +``` + +Example Output: + +```bash +{ + "proposals": [ + { + "id": "1", + "messages": [ + {"@type":"/cosmos.bank.v1beta1.MsgSend","amount":[{"denom":"stake","amount":"10"}],"fromAddress":"cosmos1..","toAddress":"cosmos1.."} + ], + "status": "PROPOSAL_STATUS_VOTING_PERIOD", + "finalTallyResult": { + "yesCount": "0", + "abstainCount": "0", + "noCount": "0", + "noWithVetoCount": "0" + }, + "submitTime": "2022-03-28T11:50:20.819676256Z", + "depositEndTime": "2022-03-30T11:50:20.819676256Z", + "totalDeposit": [ + { + "denom": "stake", + "amount": "10000000010" + } + ], + "votingStartTime": "2022-03-28T14:25:26.644857113Z", + "votingEndTime": "2022-03-30T14:25:26.644857113Z", + "metadata": "AQ==", + "title": "Proposal Title", + "summary": "Proposal Summary" + }, + { + "id": "2", + "messages": [ + {"@type":"/cosmos.bank.v1beta1.MsgSend","amount":[{"denom":"stake","amount":"10"}],"fromAddress":"cosmos1..","toAddress":"cosmos1.."} + ], + "status": "PROPOSAL_STATUS_DEPOSIT_PERIOD", + "finalTallyResult": { + "yesCount": "0", + "abstainCount": "0", + "noCount": "0", + "noWithVetoCount": "0" + }, + "submitTime": "2022-03-28T14:02:41.165025015Z", + "depositEndTime": "2022-03-30T14:02:41.165025015Z", + "totalDeposit": [ + { + "denom": "stake", + "amount": "10" + } + ], + "metadata": "AQ==", + "title": "Proposal Title", + "summary": "Proposal Summary" + } + ], + "pagination": { + "total": "2" + } +} +``` + +#### Vote + +The `Vote` endpoint allows users to query a vote for a given proposal. + +Using legacy v1beta1: + +```bash +cosmos.gov.v1beta1.Query/Vote +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1","voter":"cosmos1.."}' \ + localhost:9090 \ + cosmos.gov.v1beta1.Query/Vote +``` + +Example Output: + +```bash +{ + "vote": { + "proposalId": "1", + "voter": "cosmos1..", + "option": "VOTE_OPTION_YES", + "options": [ + { + "option": "VOTE_OPTION_YES", + "weight": "1000000000000000000" + } + ] + } +} +``` + +Using v1: + +```bash +cosmos.gov.v1.Query/Vote +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1","voter":"cosmos1.."}' \ + localhost:9090 \ + cosmos.gov.v1.Query/Vote +``` + +Example Output: + +```bash +{ + "vote": { + "proposalId": "1", + "voter": "cosmos1..", + "option": "VOTE_OPTION_YES", + "options": [ + { + "option": "VOTE_OPTION_YES", + "weight": "1.000000000000000000" + } + ] + } +} +``` + +#### Votes + +The `Votes` endpoint allows users to query all votes for a given proposal. + +Using legacy v1beta1: + +```bash +cosmos.gov.v1beta1.Query/Votes +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1"}' \ + localhost:9090 \ + cosmos.gov.v1beta1.Query/Votes +``` + +Example Output: + +```bash +{ + "votes": [ + { + "proposalId": "1", + "voter": "cosmos1..", + "options": [ + { + "option": "VOTE_OPTION_YES", + "weight": "1000000000000000000" + } + ] + } + ], + "pagination": { + "total": "1" + } +} +``` + +Using v1: + +```bash +cosmos.gov.v1.Query/Votes +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1"}' \ + localhost:9090 \ + cosmos.gov.v1.Query/Votes +``` + +Example Output: + +```bash +{ + "votes": [ + { + "proposalId": "1", + "voter": "cosmos1..", + "options": [ + { + "option": "VOTE_OPTION_YES", + "weight": "1.000000000000000000" + } + ] + } + ], + "pagination": { + "total": "1" + } +} +``` + +#### Params + +The `Params` endpoint allows users to query all parameters for the `gov` module. + +{/* TODO: #10197 Querying governance params outputs nil values */} + +Using legacy v1beta1: + +```bash +cosmos.gov.v1beta1.Query/Params +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"params_type":"voting"}' \ + localhost:9090 \ + cosmos.gov.v1beta1.Query/Params +``` + +Example Output: + +```bash +{ + "votingParams": { + "votingPeriod": "172800s" + }, + "depositParams": { + "maxDepositPeriod": "0s" + }, + "tallyParams": { + "quorum": "MA==", + "threshold": "MA==", + "vetoThreshold": "MA==" + } +} +``` + +Using v1: + +```bash +cosmos.gov.v1.Query/Params +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"params_type":"voting"}' \ + localhost:9090 \ + cosmos.gov.v1.Query/Params +``` + +Example Output: + +```bash +{ + "votingParams": { + "votingPeriod": "172800s" + } +} +``` + +#### Deposit + +The `Deposit` endpoint allows users to query a deposit for a given proposal from a given depositor. + +Using legacy v1beta1: + +```bash +cosmos.gov.v1beta1.Query/Deposit +``` + +Example: + +```bash +grpcurl -plaintext \ + '{"proposal_id":"1","depositor":"cosmos1.."}' \ + localhost:9090 \ + cosmos.gov.v1beta1.Query/Deposit +``` + +Example Output: + +```bash +{ + "deposit": { + "proposalId": "1", + "depositor": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10000000" + } + ] + } +} +``` + +Using v1: + +```bash +cosmos.gov.v1.Query/Deposit +``` + +Example: + +```bash +grpcurl -plaintext \ + '{"proposal_id":"1","depositor":"cosmos1.."}' \ + localhost:9090 \ + cosmos.gov.v1.Query/Deposit +``` + +Example Output: + +```bash +{ + "deposit": { + "proposalId": "1", + "depositor": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10000000" + } + ] + } +} +``` + +#### deposits + +The `Deposits` endpoint allows users to query all deposits for a given proposal. + +Using legacy v1beta1: + +```bash +cosmos.gov.v1beta1.Query/Deposits +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1"}' \ + localhost:9090 \ + cosmos.gov.v1beta1.Query/Deposits +``` + +Example Output: + +```bash +{ + "deposits": [ + { + "proposalId": "1", + "depositor": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10000000" + } + ] + } + ], + "pagination": { + "total": "1" + } +} +``` + +Using v1: + +```bash +cosmos.gov.v1.Query/Deposits +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1"}' \ + localhost:9090 \ + cosmos.gov.v1.Query/Deposits +``` + +Example Output: + +```bash +{ + "deposits": [ + { + "proposalId": "1", + "depositor": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10000000" + } + ] + } + ], + "pagination": { + "total": "1" + } +} +``` + +#### TallyResult + +The `TallyResult` endpoint allows users to query the tally of a given proposal. + +Using legacy v1beta1: + +```bash +cosmos.gov.v1beta1.Query/TallyResult +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1"}' \ + localhost:9090 \ + cosmos.gov.v1beta1.Query/TallyResult +``` + +Example Output: + +```bash +{ + "tally": { + "yes": "1000000", + "abstain": "0", + "no": "0", + "noWithVeto": "0" + } +} +``` + +Using v1: + +```bash +cosmos.gov.v1.Query/TallyResult +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1"}' \ + localhost:9090 \ + cosmos.gov.v1.Query/TallyResult +``` + +Example Output: + +```bash +{ + "tally": { + "yes": "1000000", + "abstain": "0", + "no": "0", + "noWithVeto": "0" + } +} +``` + +### REST + +A user can query the `gov` module using REST endpoints. + +#### proposal + +The `proposals` endpoint allows users to query a given proposal. + +Using legacy v1beta1: + +```bash +/cosmos/gov/v1beta1/proposals/{proposal_id} +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1beta1/proposals/1 +``` + +Example Output: + +```bash +{ + "proposal": { + "proposal_id": "1", + "content": null, + "status": "PROPOSAL_STATUS_VOTING_PERIOD", + "final_tally_result": { + "yes": "0", + "abstain": "0", + "no": "0", + "no_with_veto": "0" + }, + "submit_time": "2022-03-28T11:50:20.819676256Z", + "deposit_end_time": "2022-03-30T11:50:20.819676256Z", + "total_deposit": [ + { + "denom": "stake", + "amount": "10000000010" + } + ], + "voting_start_time": "2022-03-28T14:25:26.644857113Z", + "voting_end_time": "2022-03-30T14:25:26.644857113Z" + } +} +``` + +Using v1: + +```bash +/cosmos/gov/v1/proposals/{proposal_id} +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1/proposals/1 +``` + +Example Output: + +```bash +{ + "proposal": { + "id": "1", + "messages": [ + { + "@type": "/cosmos.bank.v1beta1.MsgSend", + "from_address": "cosmos1..", + "to_address": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10" + } + ] + } + ], + "status": "PROPOSAL_STATUS_VOTING_PERIOD", + "final_tally_result": { + "yes_count": "0", + "abstain_count": "0", + "no_count": "0", + "no_with_veto_count": "0" + }, + "submit_time": "2022-03-28T11:50:20.819676256Z", + "deposit_end_time": "2022-03-30T11:50:20.819676256Z", + "total_deposit": [ + { + "denom": "stake", + "amount": "10000000" + } + ], + "voting_start_time": "2022-03-28T14:25:26.644857113Z", + "voting_end_time": "2022-03-30T14:25:26.644857113Z", + "metadata": "AQ==", + "title": "Proposal Title", + "summary": "Proposal Summary" + } +} +``` + +#### proposals + +The `proposals` endpoint also allows users to query all proposals with optional filters. + +Using legacy v1beta1: + +```bash +/cosmos/gov/v1beta1/proposals +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1beta1/proposals +``` + +Example Output: + +```bash +{ + "proposals": [ + { + "proposal_id": "1", + "content": null, + "status": "PROPOSAL_STATUS_VOTING_PERIOD", + "final_tally_result": { + "yes": "0", + "abstain": "0", + "no": "0", + "no_with_veto": "0" + }, + "submit_time": "2022-03-28T11:50:20.819676256Z", + "deposit_end_time": "2022-03-30T11:50:20.819676256Z", + "total_deposit": [ + { + "denom": "stake", + "amount": "10000000" + } + ], + "voting_start_time": "2022-03-28T14:25:26.644857113Z", + "voting_end_time": "2022-03-30T14:25:26.644857113Z" + }, + { + "proposal_id": "2", + "content": null, + "status": "PROPOSAL_STATUS_DEPOSIT_PERIOD", + "final_tally_result": { + "yes": "0", + "abstain": "0", + "no": "0", + "no_with_veto": "0" + }, + "submit_time": "2022-03-28T14:02:41.165025015Z", + "deposit_end_time": "2022-03-30T14:02:41.165025015Z", + "total_deposit": [ + { + "denom": "stake", + "amount": "10" + } + ], + "voting_start_time": "0001-01-01T00:00:00Z", + "voting_end_time": "0001-01-01T00:00:00Z" + } + ], + "pagination": { + "next_key": null, + "total": "2" + } +} +``` + +Using v1: + +```bash +/cosmos/gov/v1/proposals +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1/proposals +``` + +Example Output: + +```bash +{ + "proposals": [ + { + "id": "1", + "messages": [ + { + "@type": "/cosmos.bank.v1beta1.MsgSend", + "from_address": "cosmos1..", + "to_address": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10" + } + ] + } + ], + "status": "PROPOSAL_STATUS_VOTING_PERIOD", + "final_tally_result": { + "yes_count": "0", + "abstain_count": "0", + "no_count": "0", + "no_with_veto_count": "0" + }, + "submit_time": "2022-03-28T11:50:20.819676256Z", + "deposit_end_time": "2022-03-30T11:50:20.819676256Z", + "total_deposit": [ + { + "denom": "stake", + "amount": "10000000010" + } + ], + "voting_start_time": "2022-03-28T14:25:26.644857113Z", + "voting_end_time": "2022-03-30T14:25:26.644857113Z", + "metadata": "AQ==", + "title": "Proposal Title", + "summary": "Proposal Summary" + }, + { + "id": "2", + "messages": [ + { + "@type": "/cosmos.bank.v1beta1.MsgSend", + "from_address": "cosmos1..", + "to_address": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10" + } + ] + } + ], + "status": "PROPOSAL_STATUS_DEPOSIT_PERIOD", + "final_tally_result": { + "yes_count": "0", + "abstain_count": "0", + "no_count": "0", + "no_with_veto_count": "0" + }, + "submit_time": "2022-03-28T14:02:41.165025015Z", + "deposit_end_time": "2022-03-30T14:02:41.165025015Z", + "total_deposit": [ + { + "denom": "stake", + "amount": "10" + } + ], + "voting_start_time": null, + "voting_end_time": null, + "metadata": "AQ==", + "title": "Proposal Title", + "summary": "Proposal Summary" + } + ], + "pagination": { + "next_key": null, + "total": "2" + } +} +``` + +#### voter vote + +The `votes` endpoint allows users to query a vote for a given proposal. + +Using legacy v1beta1: + +```bash +/cosmos/gov/v1beta1/proposals/{proposal_id}/votes/{voter} +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1beta1/proposals/1/votes/cosmos1.. +``` + +Example Output: + +```bash +{ + "vote": { + "proposal_id": "1", + "voter": "cosmos1..", + "option": "VOTE_OPTION_YES", + "options": [ + { + "option": "VOTE_OPTION_YES", + "weight": "1.000000000000000000" + } + ] + } +} +``` + +Using v1: + +```bash +/cosmos/gov/v1/proposals/{proposal_id}/votes/{voter} +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1/proposals/1/votes/cosmos1.. +``` + +Example Output: + +```bash +{ + "vote": { + "proposal_id": "1", + "voter": "cosmos1..", + "options": [ + { + "option": "VOTE_OPTION_YES", + "weight": "1.000000000000000000" + } + ], + "metadata": "" + } +} +``` + +#### votes + +The `votes` endpoint allows users to query all votes for a given proposal. + +Using legacy v1beta1: + +```bash +/cosmos/gov/v1beta1/proposals/{proposal_id}/votes +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1beta1/proposals/1/votes +``` + +Example Output: + +```bash +{ + "votes": [ + { + "proposal_id": "1", + "voter": "cosmos1..", + "option": "VOTE_OPTION_YES", + "options": [ + { + "option": "VOTE_OPTION_YES", + "weight": "1.000000000000000000" + } + ] + } + ], + "pagination": { + "next_key": null, + "total": "1" + } +} +``` + +Using v1: + +```bash +/cosmos/gov/v1/proposals/{proposal_id}/votes +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1/proposals/1/votes +``` + +Example Output: + +```bash +{ + "votes": [ + { + "proposal_id": "1", + "voter": "cosmos1..", + "options": [ + { + "option": "VOTE_OPTION_YES", + "weight": "1.000000000000000000" + } + ], + "metadata": "" + } + ], + "pagination": { + "next_key": null, + "total": "1" + } +} +``` + +#### params + +The `params` endpoint allows users to query all parameters for the `gov` module. + +{/* TODO: #10197 Querying governance params outputs nil values */} + +Using legacy v1beta1: + +```bash +/cosmos/gov/v1beta1/params/{params_type} +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1beta1/params/voting +``` + +Example Output: + +```bash +{ + "voting_params": { + "voting_period": "172800s" + }, + "deposit_params": { + "min_deposit": [ + ], + "max_deposit_period": "0s" + }, + "tally_params": { + "quorum": "0.000000000000000000", + "threshold": "0.000000000000000000", + "veto_threshold": "0.000000000000000000" + } +} +``` + +Using v1: + +```bash +/cosmos/gov/v1/params/{params_type} +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1/params/voting +``` + +Example Output: + +```bash +{ + "voting_params": { + "voting_period": "172800s" + }, + "deposit_params": { + "min_deposit": [ + ], + "max_deposit_period": "0s" + }, + "tally_params": { + "quorum": "0.000000000000000000", + "threshold": "0.000000000000000000", + "veto_threshold": "0.000000000000000000" + } +} +``` + +#### deposits + +The `deposits` endpoint allows users to query a deposit for a given proposal from a given depositor. + +Using legacy v1beta1: + +```bash +/cosmos/gov/v1beta1/proposals/{proposal_id}/deposits/{depositor} +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1beta1/proposals/1/deposits/cosmos1.. +``` + +Example Output: + +```bash +{ + "deposit": { + "proposal_id": "1", + "depositor": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10000000" + } + ] + } +} +``` + +Using v1: + +```bash +/cosmos/gov/v1/proposals/{proposal_id}/deposits/{depositor} +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1/proposals/1/deposits/cosmos1.. +``` + +Example Output: + +```bash +{ + "deposit": { + "proposal_id": "1", + "depositor": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10000000" + } + ] + } +} +``` + +#### proposal deposits + +The `deposits` endpoint allows users to query all deposits for a given proposal. + +Using legacy v1beta1: + +```bash +/cosmos/gov/v1beta1/proposals/{proposal_id}/deposits +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1beta1/proposals/1/deposits +``` + +Example Output: + +```bash +{ + "deposits": [ + { + "proposal_id": "1", + "depositor": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10000000" + } + ] + } + ], + "pagination": { + "next_key": null, + "total": "1" + } +} +``` + +Using v1: + +```bash +/cosmos/gov/v1/proposals/{proposal_id}/deposits +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1/proposals/1/deposits +``` + +Example Output: + +```bash +{ + "deposits": [ + { + "proposal_id": "1", + "depositor": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10000000" + } + ] + } + ], + "pagination": { + "next_key": null, + "total": "1" + } +} +``` + +#### tally + +The `tally` endpoint allows users to query the tally of a given proposal. + +Using legacy v1beta1: + +```bash +/cosmos/gov/v1beta1/proposals/{proposal_id}/tally +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1beta1/proposals/1/tally +``` + +Example Output: + +```bash +{ + "tally": { + "yes": "1000000", + "abstain": "0", + "no": "0", + "no_with_veto": "0" + } +} +``` + +Using v1: + +```bash +/cosmos/gov/v1/proposals/{proposal_id}/tally +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1/proposals/1/tally +``` + +Example Output: + +```bash +{ + "tally": { + "yes": "1000000", + "abstain": "0", + "no": "0", + "no_with_veto": "0" + } +} +``` + +## Metadata + +The gov module has two locations for metadata where users can provide further context about the on-chain actions they are taking. By default all metadata fields have a 255 character length field where metadata can be stored in json format, either on-chain or off-chain depending on the amount of data required. Here we provide a recommendation for the json structure and where the data should be stored. There are two important factors in making these recommendations. First, that the gov and group modules are consistent with one another, note the number of proposals made by all groups may be quite large. Second, that client applications such as block explorers and governance interfaces have confidence in the consistency of metadata structure accross chains. + +### Proposal + +Location: off-chain as json object stored on IPFS (mirrors [group proposal](../group/#metadata)) + +```json +{ + "title": "", + "authors": [""], + "summary": "", + "details": "", + "proposal_forum_url": "", + "vote_option_context": "", +} +``` + +:::note +The `authors` field is an array of strings, this is to allow for multiple authors to be listed in the metadata. +In v0.46, the `authors` field is a comma-separated string. Frontends are encouraged to support both formats for backwards compatibility. +::: + +### Vote + +Location: on-chain as json within 255 character limit (mirrors [group vote](../group/#metadata)) + +```json +{ + "justification": "", +} +``` + +## Future Improvements + +The current documentation only describes the minimum viable product for the +governance module. Future improvements may include: + +* **`BountyProposals`:** If accepted, a `BountyProposal` creates an open + bounty. The `BountyProposal` specifies how many Atoms will be given upon + completion. These Atoms will be taken from the `reserve pool`. After a + `BountyProposal` is accepted by governance, anybody can submit a + `SoftwareUpgradeProposal` with the code to claim the bounty. Note that once a + `BountyProposal` is accepted, the corresponding funds in the `reserve pool` + are locked so that payment can always be honored. In order to link a + `SoftwareUpgradeProposal` to an open bounty, the submitter of the + `SoftwareUpgradeProposal` will use the `Proposal.LinkedProposal` attribute. + If a `SoftwareUpgradeProposal` linked to an open bounty is accepted by + governance, the funds that were reserved are automatically transferred to the + submitter. +* **Complex delegation:** Delegators could choose other representatives than + their validators. Ultimately, the chain of representatives would always end + up to a validator, but delegators could inherit the vote of their chosen + representative before they inherit the vote of their validator. In other + words, they would only inherit the vote of their validator if their other + appointed representative did not vote. +* **Better process for proposal review:** There would be two parts to + `proposal.Deposit`, one for anti-spam (same as in MVP) and an other one to + reward third party auditors. diff --git a/.gitbook/developers-native/core/gov.mdx b/.gitbook/developers-native/core/gov/index.mde similarity index 100% rename from .gitbook/developers-native/core/gov.mdx rename to .gitbook/developers-native/core/gov/index.mde diff --git a/.gitbook/developers-native/core/group.mdx b/.gitbook/developers-native/core/group/index.md similarity index 99% rename from .gitbook/developers-native/core/group.mdx rename to .gitbook/developers-native/core/group/index.md index e2be16d..3e70cfe 100644 --- a/.gitbook/developers-native/core/group.mdx +++ b/.gitbook/developers-native/core/group/index.md @@ -2113,7 +2113,7 @@ The group module has four locations for metadata where users can provide further ### Proposal -Location: off-chain as json object stored on IPFS (mirrors [gov proposal](../gov/README.md#metadata)) +Location: off-chain as json object stored on IPFS (mirrors [gov proposal](../gov/#metadata)) ```json { @@ -2133,7 +2133,7 @@ In v0.46, the `authors` field is a comma-separated string. Frontends are encoura ### Vote -Location: on-chain as json within 255 character limit (mirrors [gov vote](../gov/README.md#metadata)) +Location: on-chain as json within 255 character limit (mirrors [gov vote](../gov/#metadata)) ```json { diff --git a/.gitbook/developers-native/core/index.md b/.gitbook/developers-native/core/index.md new file mode 100644 index 0000000..dc0a11b --- /dev/null +++ b/.gitbook/developers-native/core/index.md @@ -0,0 +1,3 @@ +# Core + +## Core Modules diff --git a/.gitbook/developers-native/core/mint.mdx b/.gitbook/developers-native/core/mint/index.md similarity index 83% rename from .gitbook/developers-native/core/mint.mdx rename to .gitbook/developers-native/core/mint/index.md index e8c0829..8019801 100644 --- a/.gitbook/developers-native/core/mint.mdx +++ b/.gitbook/developers-native/core/mint/index.md @@ -2,24 +2,24 @@ sidebar_position: 1 --- -# Mint +# `x/mint` ## Contents -* [State](./#state) - * [Minter](./#minter) - * [Params](./#params) -* [Begin-Block](./#begin-block) - * [NextInflationRate](./#nextinflationrate) - * [NextAnnualProvisions](./#nextannualprovisions) - * [BlockProvision](./#blockprovision) -* [Parameters](./#parameters) -* [Events](./#events) - * [BeginBlocker](./#beginblocker) -* [Client](./#client) - * [CLI](./#cli) - * [gRPC](./#grpc) - * [REST](./#rest) +* [State](#state) + * [Minter](#minter) + * [Params](#params) +* [Begin-Block](#begin-block) + * [NextInflationRate](#nextinflationrate) + * [NextAnnualProvisions](#nextannualprovisions) + * [BlockProvision](#blockprovision) +* [Parameters](#parameters) +* [Events](#events) + * [BeginBlocker](#beginblocker) +* [Client](#client) + * [CLI](#cli) + * [gRPC](#grpc) + * [REST](#rest) ## Concepts @@ -30,21 +30,22 @@ The minting mechanism was designed to: * allow for a flexible inflation rate determined by market demand targeting a particular bonded-stake ratio * effect a balance between market liquidity and staked supply -In order to best determine the appropriate market rate for inflation rewards, a\ -moving change rate is used. The moving change rate mechanism ensures that if\ -the % bonded is either over or under the goal %-bonded, the inflation rate will\ -adjust to further incentivize or disincentivize being bonded, respectively. Setting the goal\ -%-bonded at less than 100% encourages the network to maintain some non-staked tokens\ +In order to best determine the appropriate market rate for inflation rewards, a +moving change rate is used. The moving change rate mechanism ensures that if +the % bonded is either over or under the goal %-bonded, the inflation rate will +adjust to further incentivize or disincentivize being bonded, respectively. Setting the goal +%-bonded at less than 100% encourages the network to maintain some non-staked tokens which should help provide some liquidity. It can be broken down in the following way: -* If the actual percentage of bonded tokens is below the goal %-bonded the inflation rate will\ - increase until a maximum value is reached -* If the goal % bonded (67% in Cosmos-Hub) is maintained, then the inflation\ - rate will stay constant -* If the actual percentage of bonded tokens is above the goal %-bonded the inflation rate will\ - decrease until a minimum value is reached +* If the actual percentage of bonded tokens is below the goal %-bonded the inflation rate will + increase until a maximum value is reached +* If the goal % bonded (67% in Cosmos-Hub) is maintained, then the inflation + rate will stay constant +* If the actual percentage of bonded tokens is above the goal %-bonded the inflation rate will + decrease until a minimum value is reached + ## State @@ -54,18 +55,18 @@ The minter is a space for holding current inflation information. * Minter: `0x00 -> ProtocolBuffer(minter)` -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/mint/v1beta1/mint.proto#L10-L24 ``` ### Params -The mint module stores its params in state with the prefix of `0x01`,\ +The mint module stores its params in state with the prefix of `0x01`, it can be updated with governance or the address with authority. * Params: `mint/params -> legacy_amino(params)` -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/mint/v1beta1/mint.proto#L26-L59 ``` @@ -75,10 +76,10 @@ Minting parameters are recalculated and inflation paid at the beginning of each ### Inflation rate calculation -Inflation rate is calculated using an "inflation calculation function" that's\ -passed to the `NewAppModule` function. If no function is passed, then the SDK's\ -default inflation function will be used (`NextInflationRate`). In case a custom\ -inflation calculation logic is needed, this can be achieved by defining and\ +Inflation rate is calculated using an "inflation calculation function" that's +passed to the `NewAppModule` function. If no function is passed, then the SDK's +default inflation function will be used (`NextInflationRate`). In case a custom +inflation calculation logic is needed, this can be achieved by defining and passing a function that matches `InflationCalculationFn`'s signature. ```go @@ -87,10 +88,10 @@ type InflationCalculationFn func(ctx sdk.Context, minter Minter, params Params, #### NextInflationRate -The target annual inflation rate is recalculated each block.\ -The inflation is also subject to a rate change (positive or negative)\ -depending on the distance from the desired ratio (67%). The maximum rate change\ -possible is defined to be 13% per year, however, the annual inflation is capped\ +The target annual inflation rate is recalculated each block. +The inflation is also subject to a rate change (positive or negative) +depending on the distance from the desired ratio (67%). The maximum rate change +possible is defined to be 13% per year, however, the annual inflation is capped as between 7% and 20%. ```go @@ -113,7 +114,7 @@ NextInflationRate(params Params, bondedRatio math.LegacyDec) (inflation math.Leg ### NextAnnualProvisions -Calculate the annual provisions based on current total supply and inflation\ +Calculate the annual provisions based on current total supply and inflation rate. This parameter is calculated once per block. ```go @@ -131,12 +132,13 @@ BlockProvision(params Params) sdk.Coin { return sdk.NewCoin(params.MintDenom, provisionAmt.Truncate()) ``` + ## Parameters The minting module contains the following parameters: | Key | Type | Example | -| ------------------- | --------------- | ---------------------- | +|---------------------|-----------------|------------------------| | MintDenom | string | "uatom" | | InflationRateChange | string (dec) | "0.130000000000000000" | | InflationMax | string (dec) | "0.200000000000000000" | @@ -144,18 +146,20 @@ The minting module contains the following parameters: | GoalBonded | string (dec) | "0.670000000000000000" | | BlocksPerYear | string (uint64) | "6311520" | + ## Events The minting module emits the following events: ### BeginBlocker -| Type | Attribute Key | Attribute Value | -| ---- | ------------------ | ------------------ | -| mint | bonded\_ratio | {bondedRatio} | -| mint | inflation | {inflation} | -| mint | annual\_provisions | {annualProvisions} | -| mint | amount | {amount} | +| Type | Attribute Key | Attribute Value | +|------|-------------------|--------------------| +| mint | bonded_ratio | {bondedRatio} | +| mint | inflation | {inflation} | +| mint | annual_provisions | {annualProvisions} | +| mint | amount | {amount} | + ## Client @@ -171,7 +175,7 @@ The `query` commands allows users to query `mint` state. simd query mint --help ``` -**annual-provisions** +##### annual-provisions The `annual-provisions` command allows users to query the current minting annual provisions value @@ -191,7 +195,7 @@ Example Output: 22268504368893.612100895088410693 ``` -**inflation** +##### inflation The `inflation` command allows users to query the current minting inflation value @@ -211,7 +215,7 @@ Example Output: 0.199200302563256955 ``` -**params** +##### params The `params` command allows users to query the current minting parameters diff --git a/.gitbook/developers-native/core/nft.mdx b/.gitbook/developers-native/core/nft/index.md similarity index 87% rename from .gitbook/developers-native/core/nft.mdx rename to .gitbook/developers-native/core/nft/index.md index 7c4aea7..34c1d40 100644 --- a/.gitbook/developers-native/core/nft.mdx +++ b/.gitbook/developers-native/core/nft/index.md @@ -2,7 +2,7 @@ sidebar_position: 1 --- -# NFT +# `x/nft` ## Contents @@ -10,18 +10,18 @@ sidebar_position: 1 `x/nft` is an implementation of a Cosmos SDK module, per [ADR 43](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-043-nft-module.md), that allows you to create nft classification, create nft, transfer nft, update nft, and support various queries by integrating the module. It is fully compatible with the ERC721 specification. -* [Concepts](./#concepts) - * [Class](./#class) - * [NFT](./#nft) -* [State](./#state) - * [Class](./#class-1) - * [NFT](./#nft-1) - * [NFTOfClassByOwner](./#nftofclassbyowner) - * [Owner](./#owner) - * [TotalSupply](./#totalsupply) -* [Messages](./#messages) - * [MsgSend](./#msgsend) -* [Events](./#events) +* [Concepts](#concepts) + * [Class](#class) + * [NFT](#nft) +* [State](#state) + * [Class](#class-1) + * [NFT](#nft-1) + * [NFTOfClassByOwner](#nftofclassbyowner) + * [Owner](#owner) + * [TotalSupply](#totalsupply) +* [Messages](#messages) + * [MsgSend](#msgsend) +* [Events](#events) ## Concepts @@ -57,7 +57,7 @@ NFTOfClassByOwner is mainly to realize the function of querying all nfts using c Since there is no extra field in NFT to indicate the owner of nft, an additional key-value pair is used to save the ownership of nft. With the transfer of nft, the key-value pair is updated synchronously. -* OwnerKey: `0x04 | classID | 0x00 | nftID |-> owner` +* OwnerKey: `0x04 | classID | 0x00 | nftID |-> owner` ### TotalSupply @@ -69,9 +69,9 @@ TotalSupply is responsible for tracking the number of all nfts under a certain c In this section we describe the processing of messages for the NFT module. -:::warning\ -The validation of `ClassID` and `NftID` is left to the app developer.\ -The SDK does not provide any validation for these fields.\ +:::warning +The validation of `ClassID` and `NftID` is left to the app developer. +The SDK does not provide any validation for these fields. ::: ### MsgSend diff --git a/.gitbook/developers-native/core/params.mdx b/.gitbook/developers-native/core/params/index.md similarity index 70% rename from .gitbook/developers-native/core/params.mdx rename to .gitbook/developers-native/core/params/index.md index 59f3d42..f8d374d 100644 --- a/.gitbook/developers-native/core/params.mdx +++ b/.gitbook/developers-native/core/params/index.md @@ -2,34 +2,34 @@ sidebar_position: 1 --- -# Params +# `x/params` -> Note: The Params module has been depreacted in favour of each module housing its own parameters. +> Note: The Params module has been depreacted in favour of each module housing its own parameters. ## Abstract Package params provides a globally available parameter store. -There are two main types, Keeper and Subspace. Subspace is an isolated namespace for a\ -paramstore, where keys are prefixed by preconfigured spacename. Keeper has a\ +There are two main types, Keeper and Subspace. Subspace is an isolated namespace for a +paramstore, where keys are prefixed by preconfigured spacename. Keeper has a permission to access all existing spaces. -Subspace can be used by the individual keepers, which need a private parameter store\ +Subspace can be used by the individual keepers, which need a private parameter store that the other keepers cannot modify. The params Keeper can be used to add a route to `x/gov` router in order to modify any parameter in case a proposal passes. The following contents explains how to use params module for master and user modules. ## Contents -* [Keeper](./#keeper) -* [Subspace](./#subspace) - * [Key](./#key) - * [KeyTable](./#keytable) - * [ParamSet](./#paramset) +* [Keeper](#keeper) +* [Subspace](#subspace) + * [Key](#key) + * [KeyTable](#keytable) + * [ParamSet](#paramset) ## Keeper -In the app initialization stage, [subspaces](./#subspace) can be allocated for other modules' keeper using `Keeper.Subspace` and are stored in `Keeper.spaces`. Then, those modules can have a reference to their specific parameter store through `Keeper.GetSubspace`. +In the app initialization stage, [subspaces](#subspace) can be allocated for other modules' keeper using `Keeper.Subspace` and are stored in `Keeper.spaces`. Then, those modules can have a reference to their specific parameter store through `Keeper.GetSubspace`. Example: @@ -45,31 +45,33 @@ func (k ExampleKeeper) SetParams(ctx sdk.Context, params types.Params) { ## Subspace -`Subspace` is a prefixed subspace of the parameter store. Each module which uses the\ +`Subspace` is a prefixed subspace of the parameter store. Each module which uses the parameter store will take a `Subspace` to isolate permission to access. ### Key -Parameter keys are human readable alphanumeric strings. A parameter for the key`"ExampleParameter"` is stored under `[]byte("SubspaceName" + "/" + "ExampleParameter")`,\ -where `"SubspaceName"` is the name of the subspace. +Parameter keys are human readable alphanumeric strings. A parameter for the key +`"ExampleParameter"` is stored under `[]byte("SubspaceName" + "/" + "ExampleParameter")`, + where `"SubspaceName"` is the name of the subspace. -Subkeys are secondary parameter keys those are used along with a primary parameter key.\ +Subkeys are secondary parameter keys those are used along with a primary parameter key. Subkeys can be used for grouping or dynamic parameter key generation during runtime. ### KeyTable -All of the parameter keys that will be used should be registered at the compile\ +All of the parameter keys that will be used should be registered at the compile time. `KeyTable` is essentially a `map[string]attribute`, where the `string` is a parameter key. -Currently, `attribute` consists of a `reflect.Type`, which indicates the parameter\ +Currently, `attribute` consists of a `reflect.Type`, which indicates the parameter type to check that provided key and value are compatible and registered, as well as a function `ValueValidatorFn` to validate values. -Only primary keys have to be registered on the `KeyTable`. Subkeys inherit the\ +Only primary keys have to be registered on the `KeyTable`. Subkeys inherit the attribute of the primary key. ### ParamSet -Modules often define parameters as a proto message. The generated struct can implement`ParamSet` interface to be used with the following methods: +Modules often define parameters as a proto message. The generated struct can implement +`ParamSet` interface to be used with the following methods: * `KeyTable.RegisterParamSet()`: registers all parameters in the struct * `Subspace.{Get, Set}ParamSet()`: Get to & Set from the struct diff --git a/.gitbook/developers-native/core/slashing.mdx b/.gitbook/developers-native/core/slashing/index.md similarity index 85% rename from .gitbook/developers-native/core/slashing.mdx rename to .gitbook/developers-native/core/slashing/index.md index 5a22bae..c62804e 100644 --- a/.gitbook/developers-native/core/slashing.mdx +++ b/.gitbook/developers-native/core/slashing/index.md @@ -2,14 +2,14 @@ sidebar_position: 1 --- -# Slashing +# `x/slashing` ## Abstract -This section specifies the slashing module of the Cosmos SDK, which implements functionality\ +This section specifies the slashing module of the Cosmos SDK, which implements functionality first outlined in the [Cosmos Whitepaper](https://cosmos.network/about/whitepaper) in June 2016. -The slashing module enables Cosmos SDK-based blockchains to disincentivize any attributable action\ +The slashing module enables Cosmos SDK-based blockchains to disincentivize any attributable action by a protocol-recognized actor with value at stake by penalizing them ("slashing"). Penalties may include, but are not limited to: @@ -21,91 +21,91 @@ This module will be used by the Cosmos Hub, the first hub in the Cosmos ecosyste ## Contents -* [Concepts](./#concepts) - * [States](./#states) - * [Tombstone Caps](./#tombstone-caps) - * [Infraction Timelines](./#infraction-timelines) -* [State](./#state) - * [Signing Info (Liveness)](./#signing-info-liveness) - * [Params](./#params) -* [Messages](./#messages) - * [Unjail](./#unjail) -* [BeginBlock](./#beginblock) - * [Liveness Tracking](./#liveness-tracking) -* [Hooks](./#hooks) -* [Events](./#events) -* [Staking Tombstone](./#staking-tombstone) -* [Parameters](./#parameters) -* [CLI](./#cli) - * [Query](./#query) - * [Transactions](./#transactions) - * [gRPC](./#grpc) - * [REST](./#rest) +* [Concepts](#concepts) + * [States](#states) + * [Tombstone Caps](#tombstone-caps) + * [Infraction Timelines](#infraction-timelines) +* [State](#state) + * [Signing Info (Liveness)](#signing-info-liveness) + * [Params](#params) +* [Messages](#messages) + * [Unjail](#unjail) +* [BeginBlock](#beginblock) + * [Liveness Tracking](#liveness-tracking) +* [Hooks](#hooks) +* [Events](#events) +* [Staking Tombstone](#staking-tombstone) +* [Parameters](#parameters) +* [CLI](#cli) + * [Query](#query) + * [Transactions](#transactions) + * [gRPC](#grpc) + * [REST](#rest) ## Concepts ### States -At any given time, there are any number of validators registered in the state\ -machine. Each block, the top `MaxValidators` (defined by `x/staking`) validators\ -who are not jailed become _bonded_, meaning that they may propose and vote on\ -blocks. Validators who are _bonded_ are _at stake_, meaning that part or all of\ +At any given time, there are any number of validators registered in the state +machine. Each block, the top `MaxValidators` (defined by `x/staking`) validators +who are not jailed become _bonded_, meaning that they may propose and vote on +blocks. Validators who are _bonded_ are _at stake_, meaning that part or all of their stake and their delegators' stake is at risk if they commit a protocol fault. -For each of these validators we keep a `ValidatorSigningInfo` record that contains\ -information partaining to validator's liveness and other infraction related\ +For each of these validators we keep a `ValidatorSigningInfo` record that contains +information partaining to validator's liveness and other infraction related attributes. ### Tombstone Caps -In order to mitigate the impact of initially likely categories of non-malicious\ -protocol faults, the Cosmos Hub implements for each validator\ -a _tombstone_ cap, which only allows a validator to be slashed once for a double\ -sign fault. For example, if you misconfigure your HSM and double-sign a bunch of\ -old blocks, you'll only be punished for the first double-sign (and then immediately tombstombed). This will still be quite expensive and desirable to avoid, but tombstone caps\ +In order to mitigate the impact of initially likely categories of non-malicious +protocol faults, the Cosmos Hub implements for each validator +a _tombstone_ cap, which only allows a validator to be slashed once for a double +sign fault. For example, if you misconfigure your HSM and double-sign a bunch of +old blocks, you'll only be punished for the first double-sign (and then immediately tombstombed). This will still be quite expensive and desirable to avoid, but tombstone caps somewhat blunt the economic impact of unintentional misconfiguration. Liveness faults do not have caps, as they can't stack upon each other. Liveness bugs are "detected" as soon as the infraction occurs, and the validators are immediately put in jail, so it is not possible for them to commit multiple liveness faults without unjailing in between. ### Infraction Timelines -To illustrate how the `x/slashing` module handles submitted evidence through\ +To illustrate how the `x/slashing` module handles submitted evidence through CometBFT consensus, consider the following examples: **Definitions**: -_\[_ : timeline start\ -&#xNAN;_]_ : timeline end\ -&#xNAN;_C__n_ : infraction `n` committed\ -&#xNAN;_D__n_ : infraction `n` discovered\ -&#xNAN;_V__b_ : validator bonded\ -&#xNAN;_V__u_ : validator unbonded +_[_ : timeline start +_]_ : timeline end +_Cn_ : infraction `n` committed +_Dn_ : infraction `n` discovered +_Vb_ : validator bonded +_Vu_ : validator unbonded #### Single Double Sign Infraction -\[----------C1----D1,Vu-----] +\[----------C1----D1,Vu-----\] -A single infraction is committed then later discovered, at which point the\ +A single infraction is committed then later discovered, at which point the validator is unbonded and slashed at the full amount for the infraction. #### Multiple Double Sign Infractions -\[----------C1--C2---C3---D1,D2,D3Vu-----] +\[----------C1--C2---C3---D1,D2,D3Vu-----\] -Multiple infractions are committed and then later discovered, at which point the\ -validator is jailed and slashed for only one infraction. Because the validator\ +Multiple infractions are committed and then later discovered, at which point the +validator is jailed and slashed for only one infraction. Because the validator is also tombstoned, they can not rejoin the validator set. ## State ### Signing Info (Liveness) -Every block includes a set of precommits by the validators for the previous block,\ -known as the `LastCommitInfo` provided by CometBFT. A `LastCommitInfo` is valid so\ +Every block includes a set of precommits by the validators for the previous block, +known as the `LastCommitInfo` provided by CometBFT. A `LastCommitInfo` is valid so long as it contains precommits from +2/3 of total voting power. -Proposers are incentivized to include precommits from all validators in the CometBFT `LastCommitInfo`\ -by receiving additional fees proportional to the difference between the voting\ +Proposers are incentivized to include precommits from all validators in the CometBFT `LastCommitInfo` +by receiving additional fees proportional to the difference between the voting power included in the `LastCommitInfo` and +2/3 (see [fee distribution](../distribution/#begin-block)). ```go @@ -115,45 +115,45 @@ type LastCommitInfo struct { } ``` -Validators are penalized for failing to be included in the `LastCommitInfo` for some\ +Validators are penalized for failing to be included in the `LastCommitInfo` for some number of blocks by being automatically jailed, potentially slashed, and unbonded. -Information about validator's liveness activity is tracked through `ValidatorSigningInfo`.\ +Information about validator's liveness activity is tracked through `ValidatorSigningInfo`. It is indexed in the store as follows: * ValidatorSigningInfo: `0x01 | ConsAddrLen (1 byte) | ConsAddress -> ProtocolBuffer(ValSigningInfo)` * MissedBlocksBitArray: `0x02 | ConsAddrLen (1 byte) | ConsAddress | LittleEndianUint64(signArrayIndex) -> VarInt(didMiss)` (varint is a number encoding format) -The first mapping allows us to easily lookup the recent signing info for a\ +The first mapping allows us to easily lookup the recent signing info for a validator based on the validator's consensus address. -The second mapping (`MissedBlocksBitArray`) acts\ -as a bit-array of size `SignedBlocksWindow` that tells us if the validator missed\ -the block for a given index in the bit-array. The index in the bit-array is given\ -as little endian uint64.\ -The result is a `varint` that takes on `0` or `1`, where `0` indicates the\ -validator did not miss (did sign) the corresponding block, and `1` indicates\ +The second mapping (`MissedBlocksBitArray`) acts +as a bit-array of size `SignedBlocksWindow` that tells us if the validator missed +the block for a given index in the bit-array. The index in the bit-array is given +as little endian uint64. +The result is a `varint` that takes on `0` or `1`, where `0` indicates the +validator did not miss (did sign) the corresponding block, and `1` indicates they missed the block (did not sign). -Note that the `MissedBlocksBitArray` is not explicitly initialized up-front. Keys\ -are added as we progress through the first `SignedBlocksWindow` blocks for a newly\ -bonded validator. The `SignedBlocksWindow` parameter defines the size\ +Note that the `MissedBlocksBitArray` is not explicitly initialized up-front. Keys +are added as we progress through the first `SignedBlocksWindow` blocks for a newly +bonded validator. The `SignedBlocksWindow` parameter defines the size (number of blocks) of the sliding window used to track validator liveness. The information stored for tracking validator liveness is as follows: -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/slashing/v1beta1/slashing.proto#L13-L35 ``` ### Params -The slashing module stores it's params in state with the prefix of `0x00`,\ +The slashing module stores it's params in state with the prefix of `0x00`, it can be updated with governance or the address with authority. * Params: `0x00 | ProtocolBuffer(Params)` -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/slashing/v1beta1/slashing.proto#L37-L59 ``` @@ -163,7 +163,7 @@ In this section we describe the processing of messages for the `slashing` module ### Unjail -If a validator was automatically unbonded due to downtime and wishes to come back online &\ +If a validator was automatically unbonded due to downtime and wishes to come back online & possibly rejoin the bonded set, it must send `MsgUnjail`: ```protobuf @@ -201,25 +201,30 @@ unjail(tx MsgUnjail) return ``` -If the validator has enough stake to be in the top `n = MaximumBondedValidators`, it will be automatically rebonded,\ -and all delegators still delegated to the validator will be rebonded and begin to again collect\ +If the validator has enough stake to be in the top `n = MaximumBondedValidators`, it will be automatically rebonded, +and all delegators still delegated to the validator will be rebonded and begin to again collect provisions and rewards. ## BeginBlock ### Liveness Tracking -At the beginning of each block, we update the `ValidatorSigningInfo` for each\ -validator and check if they've crossed below the liveness threshold over a\ -sliding window. This sliding window is defined by `SignedBlocksWindow` and the\ -index in this window is determined by `IndexOffset` found in the validator's`ValidatorSigningInfo`. For each block processed, the `IndexOffset` is incremented\ -regardless if the validator signed or not. Once the index is determined, the`MissedBlocksBitArray` and `MissedBlocksCounter` are updated accordingly. - -Finally, in order to determine if a validator crosses below the liveness threshold,\ -we fetch the maximum number of blocks missed, `maxMissed`, which is`SignedBlocksWindow - (MinSignedPerWindow * SignedBlocksWindow)` and the minimum\ -height at which we can determine liveness, `minHeight`. If the current block is\ -greater than `minHeight` and the validator's `MissedBlocksCounter` is greater than`maxMissed`, they will be slashed by `SlashFractionDowntime`, will be jailed\ -for `DowntimeJailDuration`, and have the following values reset:`MissedBlocksBitArray`, `MissedBlocksCounter`, and `IndexOffset`. +At the beginning of each block, we update the `ValidatorSigningInfo` for each +validator and check if they've crossed below the liveness threshold over a +sliding window. This sliding window is defined by `SignedBlocksWindow` and the +index in this window is determined by `IndexOffset` found in the validator's +`ValidatorSigningInfo`. For each block processed, the `IndexOffset` is incremented +regardless if the validator signed or not. Once the index is determined, the +`MissedBlocksBitArray` and `MissedBlocksCounter` are updated accordingly. + +Finally, in order to determine if a validator crosses below the liveness threshold, +we fetch the maximum number of blocks missed, `maxMissed`, which is +`SignedBlocksWindow - (MinSignedPerWindow * SignedBlocksWindow)` and the minimum +height at which we can determine liveness, `minHeight`. If the current block is +greater than `minHeight` and the validator's `MissedBlocksCounter` is greater than +`maxMissed`, they will be slashed by `SlashFractionDowntime`, will be jailed +for `DowntimeJailDuration`, and have the following values reset: +`MissedBlocksBitArray`, `MissedBlocksCounter`, and `IndexOffset`. **Note**: Liveness slashes do **NOT** lead to a tombstombing. @@ -311,7 +316,7 @@ The following hooks impact the slashing state: ### Validator Bonded -Upon successful first-time bonding of a new validator, we create a new `ValidatorSigningInfo` structure for the\ +Upon successful first-time bonding of a new validator, we create a new `ValidatorSigningInfo` structure for the now-bonded validator, which `StartHeight` of the current block. If the validator was out of the validator set and gets bonded again, its new bonded height is set. @@ -359,16 +364,16 @@ The slashing module emits the following events: | slash | address | {validatorConsensusAddress} | | slash | power | {validatorPower} | | slash | reason | {slashReason} | -| slash | jailed \[0] | {validatorConsensusAddress} | -| slash | burned coins | {math.Int} | +| slash | jailed [0] | {validatorConsensusAddress} | +| slash | burned coins | {math.Int} | -* \[0] Only included if the validator is jailed. +* [0] Only included if the validator is jailed. -| Type | Attribute Key | Attribute Value | -| -------- | -------------- | --------------------------- | -| liveness | address | {validatorConsensusAddress} | -| liveness | missed\_blocks | {missedBlocksCounter} | -| liveness | height | {blockHeight} | +| Type | Attribute Key | Attribute Value | +| -------- | ------------- | --------------------------- | +| liveness | address | {validatorConsensusAddress} | +| liveness | missed_blocks | {missedBlocksCounter} | +| liveness | height | {blockHeight} | #### Slash @@ -384,35 +389,35 @@ The slashing module emits the following events: ### Abstract -In the current implementation of the `slashing` module, when the consensus engine\ -informs the state machine of a validator's consensus fault, the validator is\ -partially slashed, and put into a "jail period", a period of time in which they\ -are not allowed to rejoin the validator set. However, because of the nature of\ -consensus faults and ABCI, there can be a delay between an infraction occurring,\ -and evidence of the infraction reaching the state machine (this is one of the\ +In the current implementation of the `slashing` module, when the consensus engine +informs the state machine of a validator's consensus fault, the validator is +partially slashed, and put into a "jail period", a period of time in which they +are not allowed to rejoin the validator set. However, because of the nature of +consensus faults and ABCI, there can be a delay between an infraction occurring, +and evidence of the infraction reaching the state machine (this is one of the primary reasons for the existence of the unbonding period). -> Note: The tombstone concept, only applies to faults that have a delay between\ -> the infraction occurring and evidence reaching the state machine. For example,\ -> evidence of a validator double signing may take a while to reach the state machine\ -> due to unpredictable evidence gossip layer delays and the ability of validators to\ -> selectively reveal double-signatures (e.g. to infrequently-online light clients).\ -> Liveness slashing, on the other hand, is detected immediately as soon as the\ -> infraction occurs, and therefore no slashing period is needed. A validator is\ -> immediately put into jail period, and they cannot commit another liveness fault\ -> until they unjail. In the future, there may be other types of byzantine faults\ -> that have delays (for example, submitting evidence of an invalid proposal as a transaction).\ -> When implemented, it will have to be decided whether these future types of\ -> byzantine faults will result in a tombstoning (and if not, the slash amounts\ +> Note: The tombstone concept, only applies to faults that have a delay between +> the infraction occurring and evidence reaching the state machine. For example, +> evidence of a validator double signing may take a while to reach the state machine +> due to unpredictable evidence gossip layer delays and the ability of validators to +> selectively reveal double-signatures (e.g. to infrequently-online light clients). +> Liveness slashing, on the other hand, is detected immediately as soon as the +> infraction occurs, and therefore no slashing period is needed. A validator is +> immediately put into jail period, and they cannot commit another liveness fault +> until they unjail. In the future, there may be other types of byzantine faults +> that have delays (for example, submitting evidence of an invalid proposal as a transaction). +> When implemented, it will have to be decided whether these future types of +> byzantine faults will result in a tombstoning (and if not, the slash amounts > will not be capped by a slashing period). -In the current system design, once a validator is put in the jail for a consensus\ -fault, after the `JailPeriod` they are allowed to send a transaction to `unjail`\ +In the current system design, once a validator is put in the jail for a consensus +fault, after the `JailPeriod` they are allowed to send a transaction to `unjail` themselves, and thus rejoin the validator set. -One of the "design desires" of the `slashing` module is that if multiple\ -infractions occur before evidence is executed (and a validator is put in jail),\ -they should only be punished for single worst infraction, but not cumulatively.\ +One of the "design desires" of the `slashing` module is that if multiple +infractions occur before evidence is executed (and a validator is put in jail), +they should only be punished for single worst infraction, but not cumulatively. For example, if the sequence of events is: 1. Validator A commits Infraction 1 (worth 30% slash) @@ -422,21 +427,21 @@ For example, if the sequence of events is: 5. Evidence for Infraction 2 reaches state machine 6. Evidence for Infraction 3 reaches state machine -Only Infraction 2 should have its slash take effect, as it is the highest. This\ -is done, so that in the case of the compromise of a validator's consensus key,\ -they will only be punished once, even if the hacker double-signs many blocks.\ -Because, the unjailing has to be done with the validator's operator key, they\ -have a chance to re-secure their consensus key, and then signal that they are\ -ready using their operator key. We call this period during which we track only\ +Only Infraction 2 should have its slash take effect, as it is the highest. This +is done, so that in the case of the compromise of a validator's consensus key, +they will only be punished once, even if the hacker double-signs many blocks. +Because, the unjailing has to be done with the validator's operator key, they +have a chance to re-secure their consensus key, and then signal that they are +ready using their operator key. We call this period during which we track only the max infraction, the "slashing period". -Once, a validator rejoins by unjailing themselves, we begin a new slashing period;\ -if they commit a new infraction after unjailing, it gets slashed cumulatively on\ +Once, a validator rejoins by unjailing themselves, we begin a new slashing period; +if they commit a new infraction after unjailing, it gets slashed cumulatively on top of the worst infraction from the previous slashing period. -However, while infractions are grouped based off of the slashing periods, because\ -evidence can be submitted up to an `unbondingPeriod` after the infraction, we\ -still have to allow for evidence to be submitted for previous slashing periods.\ +However, while infractions are grouped based off of the slashing periods, because +evidence can be submitted up to an `unbondingPeriod` after the infraction, we +still have to allow for evidence to be submitted for previous slashing periods. For example, if the sequence of events is: 1. Validator A commits Infraction 1 (worth 30% slash) @@ -444,49 +449,49 @@ For example, if the sequence of events is: 3. Evidence for Infraction 1 reaches state machine (and Validator A is put in jail) 4. Validator A unjails -We are now in a new slashing period, however we still have to keep the door open\ -for the previous infraction, as the evidence for Infraction 2 may still come in.\ -As the number of slashing periods increase, it creates more complexity as we have\ +We are now in a new slashing period, however we still have to keep the door open +for the previous infraction, as the evidence for Infraction 2 may still come in. +As the number of slashing periods increase, it creates more complexity as we have to keep track of the highest infraction amount for every single slashing period. -> Note: Currently, according to the `slashing` module spec, a new slashing period\ -> is created every time a validator is unbonded then rebonded. This should probably\ -> be changed to jailed/unjailed. See issue [#3205](https://github.com/cosmos/cosmos-sdk/issues/3205)\ -> for further details. For the remainder of this, I will assume that we only start\ +> Note: Currently, according to the `slashing` module spec, a new slashing period +> is created every time a validator is unbonded then rebonded. This should probably +> be changed to jailed/unjailed. See issue [#3205](https://github.com/cosmos/cosmos-sdk/issues/3205) +> for further details. For the remainder of this, I will assume that we only start > a new slashing period when a validator gets unjailed. -The maximum number of slashing periods is the `len(UnbondingPeriod) / len(JailPeriod)`.\ -The current defaults in Gaia for the `UnbondingPeriod` and `JailPeriod` are 3 weeks\ -and 2 days, respectively. This means there could potentially be up to 11 slashing\ -periods concurrently being tracked per validator. If we set the `JailPeriod ≥ UnbondingPeriod`,\ +The maximum number of slashing periods is the `len(UnbondingPeriod) / len(JailPeriod)`. +The current defaults in Gaia for the `UnbondingPeriod` and `JailPeriod` are 3 weeks +and 2 days, respectively. This means there could potentially be up to 11 slashing +periods concurrently being tracked per validator. If we set the `JailPeriod >= UnbondingPeriod`, we only have to track 1 slashing period (i.e not have to track slashing periods). -Currently, in the jail period implementation, once a validator unjails, all of\ -their delegators who are delegated to them (haven't unbonded / redelegated away),\ -stay with them. Given that consensus safety faults are so egregious\ -(way more so than liveness faults), it is probably prudent to have delegators not\ +Currently, in the jail period implementation, once a validator unjails, all of +their delegators who are delegated to them (haven't unbonded / redelegated away), +stay with them. Given that consensus safety faults are so egregious +(way more so than liveness faults), it is probably prudent to have delegators not "auto-rebond" to the validator. #### Proposal: infinite jail -We propose setting the "jail time" for a\ -validator who commits a consensus safety fault, to `infinite` (i.e. a tombstone state).\ -This essentially kicks the validator out of the validator set and does not allow\ -them to re-enter the validator set. All of their delegators (including the operator themselves)\ -have to either unbond or redelegate away. The validator operator can create a new\ -validator if they would like, with a new operator key and consensus key, but they\ +We propose setting the "jail time" for a +validator who commits a consensus safety fault, to `infinite` (i.e. a tombstone state). +This essentially kicks the validator out of the validator set and does not allow +them to re-enter the validator set. All of their delegators (including the operator themselves) +have to either unbond or redelegate away. The validator operator can create a new +validator if they would like, with a new operator key and consensus key, but they have to "re-earn" their delegations back. -Implementing the tombstone system and getting rid of the slashing period tracking\ -will make the `slashing` module way simpler, especially because we can remove all\ -of the hooks defined in the `slashing` module consumed by the `staking` module\ +Implementing the tombstone system and getting rid of the slashing period tracking +will make the `slashing` module way simpler, especially because we can remove all +of the hooks defined in the `slashing` module consumed by the `staking` module (the `slashing` module still consumes hooks defined in `staking`). #### Single slashing amount -Another optimization that can be made is that if we assume that all ABCI faults\ -for CometBFT consensus are slashed at the same level, we don't have to keep\ -track of "max slash". Once an ABCI fault happens, we don't have to worry about\ +Another optimization that can be made is that if we assume that all ABCI faults +for CometBFT consensus are slashed at the same level, we don't have to keep +track of "max slash". Once an ABCI fault happens, we don't have to worry about comparing potential future ones to find the max. Currently the only CometBFT ABCI fault is: @@ -497,11 +502,11 @@ It is currently planned to include the following fault in the near future: * Signing a precommit when you're in unbonding phase (needed to make light client bisection safe) -Given that these faults are both attributable byzantine faults, we will likely\ +Given that these faults are both attributable byzantine faults, we will likely want to slash them equally, and thus we can enact the above change. -> Note: This change may make sense for current CometBFT consensus, but maybe\ -> not for a different consensus algorithm or future versions of CometBFT that\ +> Note: This change may make sense for current CometBFT consensus, but maybe +> not for a different consensus algorithm or future versions of CometBFT that > may want to punish at different levels (for example, partial slashing). ## Parameters @@ -747,7 +752,7 @@ Example Output: } ``` -#### signing\_info +#### signing_info ```shell /cosmos/slashing/v1beta1/signing_infos/%s @@ -774,7 +779,7 @@ Example Output: } ``` -#### signing\_infos +#### signing_infos ```shell /cosmos/slashing/v1beta1/signing_infos diff --git a/.gitbook/developers-native/core/staking.mdx b/.gitbook/developers-native/core/staking/index.md similarity index 85% rename from .gitbook/developers-native/core/staking.mdx rename to .gitbook/developers-native/core/staking/index.md index 6bf709c..c2a15bc 100644 --- a/.gitbook/developers-native/core/staking.mdx +++ b/.gitbook/developers-native/core/staking/index.md @@ -2,63 +2,63 @@ sidebar_position: 1 --- -# Staking +# `x/staking` ## Abstract -This paper specifies the Staking module of the Cosmos SDK that was first\ -described in the [Cosmos Whitepaper](https://cosmos.network/about/whitepaper)\ +This paper specifies the Staking module of the Cosmos SDK that was first +described in the [Cosmos Whitepaper](https://cosmos.network/about/whitepaper) in June 2016. -The module enables Cosmos SDK-based blockchain to support an advanced\ -Proof-of-Stake (PoS) system. In this system, holders of the native staking token of\ -the chain can become validators and can delegate tokens to validators,\ +The module enables Cosmos SDK-based blockchain to support an advanced +Proof-of-Stake (PoS) system. In this system, holders of the native staking token of +the chain can become validators and can delegate tokens to validators, ultimately determining the effective validator set for the system. -This module is used in the Cosmos Hub, the first Hub in the Cosmos\ +This module is used in the Cosmos Hub, the first Hub in the Cosmos network. ## Contents -* [State](./#state) - * [Pool](./#pool) - * [LastTotalPower](./#lasttotalpower) - * [ValidatorUpdates](./#validatorupdates) - * [UnbondingID](./#unbondingid) - * [Params](./#params) - * [Validator](./#validator) - * [Delegation](./#delegation) - * [UnbondingDelegation](./#unbondingdelegation) - * [Redelegation](./#redelegation) - * [Queues](./#queues) - * [HistoricalInfo](./#historicalinfo) -* [State Transitions](./#state-transitions) - * [Validators](./#validators) - * [Delegations](./#delegations) - * [Slashing](./#slashing) - * [How Shares are calculated](./#how-shares-are-calculated) -* [Messages](./#messages) - * [MsgCreateValidator](./#msgcreatevalidator) - * [MsgEditValidator](./#msgeditvalidator) - * [MsgDelegate](./#msgdelegate) - * [MsgUndelegate](./#msgundelegate) - * [MsgCancelUnbondingDelegation](./#msgcancelunbondingdelegation) - * [MsgBeginRedelegate](./#msgbeginredelegate) - * [MsgUpdateParams](./#msgupdateparams) -* [Begin-Block](./#begin-block) - * [Historical Info Tracking](./#historical-info-tracking) -* [End-Block](./#end-block) - * [Validator Set Changes](./#validator-set-changes) - * [Queues](./#queues-1) -* [Hooks](./#hooks) -* [Events](./#events) - * [EndBlocker](./#endblocker) - * [Msg's](./#msgs) -* [Parameters](./#parameters) -* [Client](./#client) - * [CLI](./#cli) - * [gRPC](./#grpc) - * [REST](./#rest) +* [State](#state) + * [Pool](#pool) + * [LastTotalPower](#lasttotalpower) + * [ValidatorUpdates](#validatorupdates) + * [UnbondingID](#unbondingid) + * [Params](#params) + * [Validator](#validator) + * [Delegation](#delegation) + * [UnbondingDelegation](#unbondingdelegation) + * [Redelegation](#redelegation) + * [Queues](#queues) + * [HistoricalInfo](#historicalinfo) +* [State Transitions](#state-transitions) + * [Validators](#validators) + * [Delegations](#delegations) + * [Slashing](#slashing) + * [How Shares are calculated](#how-shares-are-calculated) +* [Messages](#messages) + * [MsgCreateValidator](#msgcreatevalidator) + * [MsgEditValidator](#msgeditvalidator) + * [MsgDelegate](#msgdelegate) + * [MsgUndelegate](#msgundelegate) + * [MsgCancelUnbondingDelegation](#msgcancelunbondingdelegation) + * [MsgBeginRedelegate](#msgbeginredelegate) + * [MsgUpdateParams](#msgupdateparams) +* [Begin-Block](#begin-block) + * [Historical Info Tracking](#historical-info-tracking) +* [End-Block](#end-block) + * [Validator Set Changes](#validator-set-changes) + * [Queues](#queues-1) +* [Hooks](#hooks) +* [Events](#events) + * [EndBlocker](#endblocker) + * [Msg's](#msgs) +* [Parameters](#parameters) +* [Client](#client) + * [CLI](#cli) + * [gRPC](#grpc) + * [REST](#rest) ## State @@ -68,14 +68,14 @@ Pool is used for tracking bonded and not-bonded token supply of the bond denomin ### LastTotalPower -LastTotalPower tracks the total amounts of bonded tokens recorded during the previous end block.\ +LastTotalPower tracks the total amounts of bonded tokens recorded during the previous end block. Store entries prefixed with "Last" must remain unchanged until EndBlock. * LastTotalPower: `0x12 -> ProtocolBuffer(math.Int)` ### ValidatorUpdates -ValidatorUpdates contains the validator updates returned to ABCI at the end of every block.\ +ValidatorUpdates contains the validator updates returned to ABCI at the end of every block. The values are overwritten in every block. * ValidatorUpdates `0x61 -> []abci.ValidatorUpdate` @@ -88,12 +88,12 @@ UnbondingID stores the ID of the latest unbonding operation. It enables creating ### Params -The staking module stores its params in state with the prefix of `0x51`,\ +The staking module stores its params in state with the prefix of `0x51`, it can be updated with governance or the address with authority. * Params: `0x51 | ProtocolBuffer(Params)` -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/staking.proto#L310-L333 ``` @@ -101,136 +101,139 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1bet Validators can have one of three statuses -* `Unbonded`: The validator is not in the active set. They cannot sign blocks and do not earn\ +* `Unbonded`: The validator is not in the active set. They cannot sign blocks and do not earn rewards. They can receive delegations. -* `Bonded`: Once the validator receives sufficient bonded tokens they automatically join the\ - active set during [`EndBlock`](./#validator-set-changes) and their status is updated to `Bonded`.\ - They are signing blocks and receiving rewards. They can receive further delegations.\ - They can be slashed for misbehavior. Delegators to this validator who unbond their delegation\ - must wait the duration of the UnbondingTime, a chain-specific param, during which time\ - they are still slashable for offences of the source validator if those offences were committed\ +* `Bonded`: Once the validator receives sufficient bonded tokens they automatically join the + active set during [`EndBlock`](#validator-set-changes) and their status is updated to `Bonded`. + They are signing blocks and receiving rewards. They can receive further delegations. + They can be slashed for misbehavior. Delegators to this validator who unbond their delegation + must wait the duration of the UnbondingTime, a chain-specific param, during which time + they are still slashable for offences of the source validator if those offences were committed during the period of time that the tokens were bonded. -* `Unbonding`: When a validator leaves the active set, either by choice or due to slashing, jailing or\ - tombstoning, an unbonding of all their delegations begins. All delegations must then wait the UnbondingTime\ +* `Unbonding`: When a validator leaves the active set, either by choice or due to slashing, jailing or + tombstoning, an unbonding of all their delegations begins. All delegations must then wait the UnbondingTime before their tokens are moved to their accounts from the `BondedPool`. -:::warning\ -Tombstoning is permanent, once tombstoned a validator's consensus key can not be reused within the chain where the tombstoning happened.\ +:::warning +Tombstoning is permanent, once tombstoned a validator's consensus key can not be reused within the chain where the tombstoning happened. ::: -Validators objects should be primarily stored and accessed by the`OperatorAddr`, an SDK validator address for the operator of the validator. Two\ -additional indices are maintained per validator object in order to fulfill\ -required lookups for slashing and validator-set updates. A third special index\ -(`LastValidatorPower`) is also maintained which however remains constant\ -throughout each block, unlike the first two indices which mirror the validator\ +Validators objects should be primarily stored and accessed by the +`OperatorAddr`, an SDK validator address for the operator of the validator. Two +additional indices are maintained per validator object in order to fulfill +required lookups for slashing and validator-set updates. A third special index +(`LastValidatorPower`) is also maintained which however remains constant +throughout each block, unlike the first two indices which mirror the validator records within a block. * Validators: `0x21 | OperatorAddrLen (1 byte) | OperatorAddr -> ProtocolBuffer(validator)` * ValidatorsByConsAddr: `0x22 | ConsAddrLen (1 byte) | ConsAddr -> OperatorAddr` * ValidatorsByPower: `0x23 | BigEndian(ConsensusPower) | OperatorAddrLen (1 byte) | OperatorAddr -> OperatorAddr` * LastValidatorsPower: `0x11 | OperatorAddrLen (1 byte) | OperatorAddr -> ProtocolBuffer(ConsensusPower)` -* ValidatorsByUnbondingID: `0x38 | UnbondingID -> 0x21 | OperatorAddrLen (1 byte) | OperatorAddr` +* ValidatorsByUnbondingID: `0x38 | UnbondingID -> 0x21 | OperatorAddrLen (1 byte) | OperatorAddr` -`Validators` is the primary index - it ensures that each operator can have only one\ -associated validator, where the public key of that validator can change in the\ -future. Delegators can refer to the immutable operator of the validator, without\ +`Validators` is the primary index - it ensures that each operator can have only one +associated validator, where the public key of that validator can change in the +future. Delegators can refer to the immutable operator of the validator, without concern for the changing public key. -`ValidatorsByUnbondingID` is an additional index that enables lookups for\ -validators by the unbonding IDs corresponding to their current unbonding. +`ValidatorsByUnbondingID` is an additional index that enables lookups for + validators by the unbonding IDs corresponding to their current unbonding. -`ValidatorByConsAddr` is an additional index that enables lookups for slashing.\ -When CometBFT reports evidence, it provides the validator address, so this\ -map is needed to find the operator. Note that the `ConsAddr` corresponds to the\ +`ValidatorByConsAddr` is an additional index that enables lookups for slashing. +When CometBFT reports evidence, it provides the validator address, so this +map is needed to find the operator. Note that the `ConsAddr` corresponds to the address which can be derived from the validator's `ConsPubKey`. -`ValidatorsByPower` is an additional index that provides a sorted list of\ -potential validators to quickly determine the current active set. Here\ -ConsensusPower is validator.Tokens/10^6 by default. Note that all validators\ +`ValidatorsByPower` is an additional index that provides a sorted list of +potential validators to quickly determine the current active set. Here +ConsensusPower is validator.Tokens/10^6 by default. Note that all validators where `Jailed` is true are not stored within this index. -`LastValidatorsPower` is a special index that provides a historical list of the\ -last-block's bonded validators. This index remains constant during a block but\ -is updated during the validator set update process which takes place in [`EndBlock`](./#end-block). +`LastValidatorsPower` is a special index that provides a historical list of the +last-block's bonded validators. This index remains constant during a block but +is updated during the validator set update process which takes place in [`EndBlock`](#end-block). Each validator's state is stored in a `Validator` struct: -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/staking.proto#L82-L138 ``` -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/staking.proto#L26-L80 ``` ### Delegation -Delegations are identified by combining `DelegatorAddr` (the address of the delegator)\ +Delegations are identified by combining `DelegatorAddr` (the address of the delegator) with the `ValidatorAddr` Delegators are indexed in the store as follows: * Delegation: `0x31 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValidatorAddrLen (1 byte) | ValidatorAddr -> ProtocolBuffer(delegation)` -Stake holders may delegate coins to validators; under this circumstance their\ -funds are held in a `Delegation` data structure. It is owned by one\ -delegator, and is associated with the shares for one validator. The sender of\ +Stake holders may delegate coins to validators; under this circumstance their +funds are held in a `Delegation` data structure. It is owned by one +delegator, and is associated with the shares for one validator. The sender of the transaction is the owner of the bond. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/staking.proto#L198-L216 ``` #### Delegator Shares -When one delegates tokens to a Validator, they are issued a number of delegator shares based on a\ -dynamic exchange rate, calculated as follows from the total number of tokens delegated to the\ +When one delegates tokens to a Validator, they are issued a number of delegator shares based on a +dynamic exchange rate, calculated as follows from the total number of tokens delegated to the validator and the number of shares issued so far: `Shares per Token = validator.TotalShares() / validator.Tokens()` -Only the number of shares received is stored on the DelegationEntry. When a delegator then\ -Undelegates, the token amount they receive is calculated from the number of shares they currently\ +Only the number of shares received is stored on the DelegationEntry. When a delegator then +Undelegates, the token amount they receive is calculated from the number of shares they currently hold and the inverse exchange rate: `Tokens per Share = validator.Tokens() / validatorShares()` -These `Shares` are simply an accounting mechanism. They are not a fungible asset. The reason for\ -this mechanism is to simplify the accounting around slashing. Rather than iteratively slashing the\ -tokens of every delegation entry, instead the Validator's total bonded tokens can be slashed,\ +These `Shares` are simply an accounting mechanism. They are not a fungible asset. The reason for +this mechanism is to simplify the accounting around slashing. Rather than iteratively slashing the +tokens of every delegation entry, instead the Validator's total bonded tokens can be slashed, effectively reducing the value of each issued delegator share. ### UnbondingDelegation -Shares in a `Delegation` can be unbonded, but they must for some time exist as\ -an `UnbondingDelegation`, where shares can be reduced if Byzantine behavior is\ +Shares in a `Delegation` can be unbonded, but they must for some time exist as +an `UnbondingDelegation`, where shares can be reduced if Byzantine behavior is detected. `UnbondingDelegation` are indexed in the store as: * UnbondingDelegation: `0x32 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValidatorAddrLen (1 byte) | ValidatorAddr -> ProtocolBuffer(unbondingDelegation)` * UnbondingDelegationsFromValidator: `0x33 | ValidatorAddrLen (1 byte) | ValidatorAddr | DelegatorAddrLen (1 byte) | DelegatorAddr -> nil` -* UnbondingDelegationByUnbondingId: `0x38 | UnbondingId -> 0x32 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValidatorAddrLen (1 byte) | ValidatorAddrUnbondingDelegation` is used in queries, to lookup all unbonding delegations for\ - a given delegator. +* UnbondingDelegationByUnbondingId: `0x38 | UnbondingId -> 0x32 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValidatorAddrLen (1 byte) | ValidatorAddr` + `UnbondingDelegation` is used in queries, to lookup all unbonding delegations for + a given delegator. -`UnbondingDelegationsFromValidator` is used in slashing, to lookup all\ -unbonding delegations associated with a given validator that need to be\ -slashed. +`UnbondingDelegationsFromValidator` is used in slashing, to lookup all + unbonding delegations associated with a given validator that need to be + slashed. + + `UnbondingDelegationByUnbondingId` is an additional index that enables + lookups for unbonding delegations by the unbonding IDs of the containing + unbonding delegation entries. -`UnbondingDelegationByUnbondingId` is an additional index that enables\ -lookups for unbonding delegations by the unbonding IDs of the containing\ -unbonding delegation entries. A UnbondingDelegation object is created every time an unbonding is initiated. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/staking.proto#L218-L261 ``` ### Redelegation -The bonded tokens worth of a `Delegation` may be instantly redelegated from a\ -source validator to a different validator (destination validator). However when\ -this occurs they must be tracked in a `Redelegation` object, whereby their\ -shares can be slashed if their tokens have contributed to a Byzantine fault\ +The bonded tokens worth of a `Delegation` may be instantly redelegated from a +source validator to a different validator (destination validator). However when +this occurs they must be tracked in a `Redelegation` object, whereby their +shares can be slashed if their tokens have contributed to a Byzantine fault committed by the source validator. `Redelegation` are indexed in the store as: @@ -240,108 +243,109 @@ committed by the source validator. * RedelegationsByDst: `0x36 | ValidatorDstAddrLen (1 byte) | ValidatorDstAddr | ValidatorSrcAddrLen (1 byte) | ValidatorSrcAddr | DelegatorAddrLen (1 byte) | DelegatorAddr -> nil` * RedelegationByUnbondingId: `0x38 | UnbondingId -> 0x34 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValidatorAddrLen (1 byte) | ValidatorSrcAddr | ValidatorDstAddr` -`Redelegations` is used for queries, to lookup all redelegations for a given\ -delegator. + `Redelegations` is used for queries, to lookup all redelegations for a given + delegator. -`RedelegationsBySrc` is used for slashing based on the `ValidatorSrcAddr`. + `RedelegationsBySrc` is used for slashing based on the `ValidatorSrcAddr`. -`RedelegationsByDst` is used for slashing based on the `ValidatorDstAddr` + `RedelegationsByDst` is used for slashing based on the `ValidatorDstAddr` -The first map here is used for queries, to lookup all redelegations for a given\ -delegator. The second map is used for slashing based on the `ValidatorSrcAddr`,\ +The first map here is used for queries, to lookup all redelegations for a given +delegator. The second map is used for slashing based on the `ValidatorSrcAddr`, while the third map is for slashing based on the `ValidatorDstAddr`. -`RedelegationByUnbondingId` is an additional index that enables\ -lookups for redelegations by the unbonding IDs of the containing\ -redelegation entries. +`RedelegationByUnbondingId` is an additional index that enables + lookups for redelegations by the unbonding IDs of the containing + redelegation entries. -A redelegation object is created every time a redelegation occurs. To prevent\ +A redelegation object is created every time a redelegation occurs. To prevent "redelegation hopping" redelegations may not occur under the situation that: -* the (re)delegator already has another immature redelegation in progress\ +* the (re)delegator already has another immature redelegation in progress with a destination to a validator (let's call it `Validator X`) -* and, the (re)delegator is attempting to create a _new_ redelegation\ +* and, the (re)delegator is attempting to create a _new_ redelegation where the source validator for this new redelegation is `Validator X`. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/staking.proto#L263-L308 ``` ### Queues -All queue objects are sorted by timestamp. The time used within any queue is\ -firstly converted to UTC, rounded to the nearest nanosecond then sorted. The sortable time format\ -used is a slight modification of the RFC3339Nano and uses the format string`"2006-01-02T15:04:05.000000000"`. Notably this format: +All queue objects are sorted by timestamp. The time used within any queue is +firstly converted to UTC, rounded to the nearest nanosecond then sorted. The sortable time format +used is a slight modification of the RFC3339Nano and uses the format string +`"2006-01-02T15:04:05.000000000"`. Notably this format: * right pads all zeros * drops the time zone info (we already use UTC) -In all cases, the stored timestamp represents the maturation time of the queue\ +In all cases, the stored timestamp represents the maturation time of the queue element. #### UnbondingDelegationQueue -For the purpose of tracking progress of unbonding delegations the unbonding\ +For the purpose of tracking progress of unbonding delegations the unbonding delegations queue is kept. * UnbondingDelegation: `0x41 | format(time) -> []DVPair` -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/staking.proto#L162-L172 ``` #### RedelegationQueue -For the purpose of tracking progress of redelegations the redelegation queue is\ +For the purpose of tracking progress of redelegations the redelegation queue is kept. * RedelegationQueue: `0x42 | format(time) -> []DVVTriplet` -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/staking.proto#L179-L191 ``` #### ValidatorQueue -For the purpose of tracking progress of unbonding validators the validator\ +For the purpose of tracking progress of unbonding validators the validator queue is kept. * ValidatorQueueTime: `0x43 | format(time) -> []sdk.ValAddress` -The stored object by each key is an array of validator operator addresses from\ -which the validator object can be accessed. Typically it is expected that only\ -a single validator record will be associated with a given timestamp however it is possible\ +The stored object by each key is an array of validator operator addresses from +which the validator object can be accessed. Typically it is expected that only +a single validator record will be associated with a given timestamp however it is possible that multiple validators exist in the queue at the same location. ### HistoricalInfo -HistoricalInfo objects are stored and pruned at each block such that the staking keeper persists\ +HistoricalInfo objects are stored and pruned at each block such that the staking keeper persists the `n` most recent historical info defined by staking module parameter: `HistoricalEntries`. -```go +```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/staking.proto#L17-L24 ``` -At each BeginBlock, the staking keeper will persist the current Header and the Validators that committed\ -the current block in a `HistoricalInfo` object. The Validators are sorted on their address to ensure that\ -they are in a deterministic order.\ -The oldest HistoricalEntries will be pruned to ensure that there only exist the parameter-defined number of\ +At each BeginBlock, the staking keeper will persist the current Header and the Validators that committed +the current block in a `HistoricalInfo` object. The Validators are sorted on their address to ensure that +they are in a deterministic order. +The oldest HistoricalEntries will be pruned to ensure that there only exist the parameter-defined number of historical entries. ## State Transitions ### Validators -State transitions in validators are performed on every [`EndBlock`](./#validator-set-changes)\ +State transitions in validators are performed on every [`EndBlock`](#validator-set-changes) in order to check for changes in the active `ValidatorSet`. -A validator can be `Unbonded`, `Unbonding` or `Bonded`. `Unbonded`\ -and `Unbonding` are collectively called `Not Bonded`. A validator can move\ +A validator can be `Unbonded`, `Unbonding` or `Bonded`. `Unbonded` +and `Unbonding` are collectively called `Not Bonded`. A validator can move directly between all the states, except for from `Bonded` to `Unbonded`. #### Not bonded to Bonded -The following transition occurs when a validator's ranking in the `ValidatorPowerIndex` surpasses\ +The following transition occurs when a validator's ranking in the `ValidatorPowerIndex` surpasses that of the `LastValidator`. * set `validator.Status` to `Bonded` @@ -364,7 +368,7 @@ When a validator begins the unbonding process the following operations occur: #### Unbonding to Unbonded -A validator moves from unbonding to unbonded when the `ValidatorQueue` object\ +A validator moves from unbonding to unbonded when the `ValidatorQueue` object moves from bonded to unbonded * update the `Validator` object for this validator @@ -372,7 +376,7 @@ moves from bonded to unbonded #### Jail/Unjail -when a validator is jailed it is effectively removed from the CometBFT set.\ +when a validator is jailed it is effectively removed from the CometBFT set. this process may be also be reversed. the following operations occur: * set `Validator.Jailed` and update object @@ -399,7 +403,7 @@ When a delegation occurs both the validator and the delegation objects are affec #### Begin Unbonding -As a part of the Undelegate and Complete Unbonding state transitions Unbond\ +As a part of the Undelegate and Complete Unbonding state transitions Unbond Delegation may be called. * subtract the unbonded shares from delegator @@ -407,7 +411,7 @@ Delegation may be called. * update the delegation or remove the delegation if there are no more shares * if the delegation is the operator of the validator and no more shares exist then trigger a jail validator * update the validator with removed the delegator shares and associated coins -* if the validator state is `Bonded`, transfer the `Coins` worth of the unbonded\ +* if the validator state is `Bonded`, transfer the `Coins` worth of the unbonded shares from the `BondedPool` to the `NotBondedPool` `ModuleAccount` * remove the validator if it is unbonded and there are no more delegation shares. * remove the validator if it is unbonded and there are no more delegation shares @@ -420,12 +424,12 @@ Delegation may be called. When a `cancel unbond delegation` occurs both the `validator`, the `delegation` and an `UnbondingDelegationQueue` state will be updated. * if cancel unbonding delegation amount equals to the `UnbondingDelegation` entry `balance`, then the `UnbondingDelegation` entry deleted from `UnbondingDelegationQueue`. -* if the `cancel unbonding delegation amount is less than the` UnbondingDelegation`entry balance, then the`UnbondingDelegation`entry will be updated with new balance in the`UnbondingDelegationQueue\`. -* cancel `amount` is [Delegated](./#delegations) back to the original `validator`. +* if the `cancel unbonding delegation amount is less than the `UnbondingDelegation` entry balance, then the `UnbondingDelegation` entry will be updated with new balance in the `UnbondingDelegationQueue`. +* cancel `amount` is [Delegated](#delegations) back to the original `validator`. #### Complete Unbonding -For undelegations which do not complete immediately, the following operations\ +For undelegations which do not complete immediately, the following operations occur when the unbonding delegation queue element matures: * remove the entry from the `UnbondingDelegation` object @@ -437,13 +441,13 @@ Redelegations affect the delegation, source and destination validators. * perform an `unbond` delegation from the source validator to retrieve the tokens worth of the unbonded shares * using the unbonded tokens, `Delegate` them to the destination validator -* if the `sourceValidator.Status` is `Bonded`, and the `destinationValidator` is not,\ +* if the `sourceValidator.Status` is `Bonded`, and the `destinationValidator` is not, transfer the newly delegated tokens from the `BondedPool` to the `NotBondedPool` `ModuleAccount` -* otherwise, if the `sourceValidator.Status` is not `Bonded`, and the `destinationValidator`\ +* otherwise, if the `sourceValidator.Status` is not `Bonded`, and the `destinationValidator` is `Bonded`, transfer the newly delegated tokens from the `NotBondedPool` to the `BondedPool` `ModuleAccount` * record the token amount in an new entry in the relevant `Redelegation` -From when a redelegation begins until it completes, the delegator is in a state of "pseudo-unbonding", and can still be\ +From when a redelegation begins until it completes, the delegator is in a state of "pseudo-unbonding", and can still be slashed for infractions that occurred before the redelegation began. #### Complete Redelegation @@ -458,65 +462,67 @@ When a redelegations complete the following occurs: When a Validator is slashed, the following occurs: -* The total `slashAmount` is calculated as the `slashFactor` (a chain parameter) \* `TokensFromConsensusPower`,\ +* The total `slashAmount` is calculated as the `slashFactor` (a chain parameter) \* `TokensFromConsensusPower`, the total number of tokens bonded to the validator at the time of the infraction. -* Every unbonding delegation and pseudo-unbonding redelegation such that the infraction occured before the unbonding or\ +* Every unbonding delegation and pseudo-unbonding redelegation such that the infraction occured before the unbonding or redelegation began from the validator are slashed by the `slashFactor` percentage of the initialBalance. -* Each amount slashed from redelegations and unbonding delegations is subtracted from the\ +* Each amount slashed from redelegations and unbonding delegations is subtracted from the total slash amount. -* The `remaingSlashAmount` is then slashed from the validator's tokens in the `BondedPool` or`NonBondedPool` depending on the validator's status. This reduces the total supply of tokens. +* The `remaingSlashAmount` is then slashed from the validator's tokens in the `BondedPool` or + `NonBondedPool` depending on the validator's status. This reduces the total supply of tokens. -In the case of a slash due to any infraction that requires evidence to submitted (for example double-sign), the slash\ -occurs at the block where the evidence is included, not at the block where the infraction occured.\ +In the case of a slash due to any infraction that requires evidence to submitted (for example double-sign), the slash +occurs at the block where the evidence is included, not at the block where the infraction occured. Put otherwise, validators are not slashed retroactively, only when they are caught. #### Slash Unbonding Delegation -When a validator is slashed, so are those unbonding delegations from the validator that began unbonding\ -after the time of the infraction. Every entry in every unbonding delegation from the validator\ -is slashed by `slashFactor`. The amount slashed is calculated from the `InitialBalance` of the\ +When a validator is slashed, so are those unbonding delegations from the validator that began unbonding +after the time of the infraction. Every entry in every unbonding delegation from the validator +is slashed by `slashFactor`. The amount slashed is calculated from the `InitialBalance` of the delegation and is capped to prevent a resulting negative balance. Completed (or mature) unbondings are not slashed. #### Slash Redelegation -When a validator is slashed, so are all redelegations from the validator that began after the\ -infraction. Redelegations are slashed by `slashFactor`.\ -Redelegations that began before the infraction are not slashed.\ -The amount slashed is calculated from the `InitialBalance` of the delegation and is capped to\ -prevent a resulting negative balance.\ +When a validator is slashed, so are all redelegations from the validator that began after the +infraction. Redelegations are slashed by `slashFactor`. +Redelegations that began before the infraction are not slashed. +The amount slashed is calculated from the `InitialBalance` of the delegation and is capped to +prevent a resulting negative balance. Mature redelegations (that have completed pseudo-unbonding) are not slashed. ### How Shares are calculated -At any given point in time, each validator has a number of tokens, `T`, and has a number of shares issued, `S`.\ -Each delegator, `i`, holds a number of shares, `S_i`.\ +At any given point in time, each validator has a number of tokens, `T`, and has a number of shares issued, `S`. +Each delegator, `i`, holds a number of shares, `S_i`. The number of tokens is the sum of all tokens delegated to the validator, plus the rewards, minus the slashes. -The delegator is entitled to a portion of the underlying tokens proportional to their proportion of shares.\ +The delegator is entitled to a portion of the underlying tokens proportional to their proportion of shares. So delegator `i` is entitled to `T * S_i / S` of the validator's tokens. -When a delegator delegates new tokens to the validator, they receive a number of shares proportional to their contribution.\ -So when delegator `j` delegates `T_j` tokens, they receive `S_j = S * T_j / T` shares.\ -The total number of tokens is now `T + T_j`, and the total number of shares is `S + S_j`.`j`s proportion of the shares is the same as their proportion of the total tokens contributed: `(S + S_j) / S = (T + T_j) / T`. +When a delegator delegates new tokens to the validator, they receive a number of shares proportional to their contribution. +So when delegator `j` delegates `T_j` tokens, they receive `S_j = S * T_j / T` shares. +The total number of tokens is now `T + T_j`, and the total number of shares is `S + S_j`. +`j`s proportion of the shares is the same as their proportion of the total tokens contributed: `(S + S_j) / S = (T + T_j) / T`. -A special case is the initial delegation, when `T = 0` and `S = 0`, so `T_j / T` is undefined.\ -For the initial delegation, delegator `j` who delegates `T_j` tokens receive `S_j = T_j` shares.\ +A special case is the initial delegation, when `T = 0` and `S = 0`, so `T_j / T` is undefined. +For the initial delegation, delegator `j` who delegates `T_j` tokens receive `S_j = T_j` shares. So a validator that hasn't received any rewards and has not been slashed will have `T = S`. ## Messages -In this section we describe the processing of the staking messages and the corresponding updates to the state. All created/modified state objects specified by each message are defined within the [state](./#state) section. +In this section we describe the processing of the staking messages and the corresponding updates to the state. All created/modified state objects specified by each message are defined within the [state](#state) section. ### MsgCreateValidator -A validator is created using the `MsgCreateValidator` message.\ +A validator is created using the `MsgCreateValidator` message. The validator must be created with an initial delegation from the operator. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L20-L21 ``` -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L50-L73 ``` @@ -526,25 +532,26 @@ This message is expected to fail if: * another validator with this pubkey is already registered * the initial self-delegation tokens are of a denom not specified as the bonding denom * the commission parameters are faulty, namely: - * `MaxRate` is either > 1 or < 0 - * the initial `Rate` is either negative or > `MaxRate` - * the initial `MaxChangeRate` is either negative or > `MaxRate` + * `MaxRate` is either > 1 or < 0 + * the initial `Rate` is either negative or > `MaxRate` + * the initial `MaxChangeRate` is either negative or > `MaxRate` * the description fields are too large -This message creates and stores the `Validator` object at appropriate indexes.\ -Additionally a self-delegation is made with the initial tokens delegation\ -tokens `Delegation`. The validator always starts as unbonded but may be bonded\ +This message creates and stores the `Validator` object at appropriate indexes. +Additionally a self-delegation is made with the initial tokens delegation +tokens `Delegation`. The validator always starts as unbonded but may be bonded in the first end-block. ### MsgEditValidator -The `Description`, `CommissionRate` of a validator can be updated using the`MsgEditValidator` message. +The `Description`, `CommissionRate` of a validator can be updated using the +`MsgEditValidator` message. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L23-L24 ``` -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L78-L97 ``` @@ -559,15 +566,15 @@ This message stores the updated `Validator` object. ### MsgDelegate -Within this message the delegator provides coins, and in return receives\ -some amount of their validator's (newly created) delegator-shares that are\ +Within this message the delegator provides coins, and in return receives +some amount of their validator's (newly created) delegator-shares that are assigned to `Delegation.Shares`. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L26-L28 ``` -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L102-L114 ``` @@ -578,37 +585,38 @@ This message is expected to fail if: * the exchange rate is invalid, meaning the validator has no tokens (due to slashing) but there are outstanding shares * the amount delegated is less than the minimum allowed delegation -If an existing `Delegation` object for provided addresses does not already\ -exist then it is created as part of this message otherwise the existing`Delegation` is updated to include the newly received shares. +If an existing `Delegation` object for provided addresses does not already +exist then it is created as part of this message otherwise the existing +`Delegation` is updated to include the newly received shares. -The delegator receives newly minted shares at the current exchange rate.\ -The exchange rate is the number of existing shares in the validator divided by\ +The delegator receives newly minted shares at the current exchange rate. +The exchange rate is the number of existing shares in the validator divided by the number of currently delegated tokens. -The validator is updated in the `ValidatorByPower` index, and the delegation is\ +The validator is updated in the `ValidatorByPower` index, and the delegation is tracked in validator object in the `Validators` index. -It is possible to delegate to a jailed validator, the only difference being it\ +It is possible to delegate to a jailed validator, the only difference being it will not be added to the power index until it is unjailed. ![Delegation sequence](https://raw.githubusercontent.com/cosmos/cosmos-sdk/release/v0.46.x/docs/uml/svg/delegation_sequence.svg) ### MsgUndelegate -The `MsgUndelegate` message allows delegators to undelegate their tokens from\ +The `MsgUndelegate` message allows delegators to undelegate their tokens from validator. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L34-L36 ``` -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L140-L152 ``` This message returns a response containing the completion time of the undelegation: -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L154-L158 ``` @@ -625,11 +633,11 @@ When this message is processed the following actions occur: * validator's `DelegatorShares` and the delegation's `Shares` are both reduced by the message `SharesAmount` * calculate the token worth of the shares remove that amount tokens held within the validator * with those removed tokens, if the validator is: - * `Bonded` - add them to an entry in `UnbondingDelegation` (create `UnbondingDelegation` if it doesn't exist) with a completion time a full unbonding period from the current time. Update pool shares to reduce BondedTokens and increase NotBondedTokens by token worth of the shares. - * `Unbonding` - add them to an entry in `UnbondingDelegation` (create `UnbondingDelegation` if it doesn't exist) with the same completion time as the validator (`UnbondingMinTime`). - * `Unbonded` - then send the coins the message `DelegatorAddr` + * `Bonded` - add them to an entry in `UnbondingDelegation` (create `UnbondingDelegation` if it doesn't exist) with a completion time a full unbonding period from the current time. Update pool shares to reduce BondedTokens and increase NotBondedTokens by token worth of the shares. + * `Unbonding` - add them to an entry in `UnbondingDelegation` (create `UnbondingDelegation` if it doesn't exist) with the same completion time as the validator (`UnbondingMinTime`). + * `Unbonded` - then send the coins the message `DelegatorAddr` * if there are no more `Shares` in the delegation, then the delegation object is removed from the store - * under this situation if the delegation is the validator's self-delegation then also jail the validator. + * under this situation if the delegation is the validator's self-delegation then also jail the validator. ![Unbond sequence](https://raw.githubusercontent.com/cosmos/cosmos-sdk/release/v0.46.x/docs/uml/svg/unbond_sequence.svg) @@ -637,11 +645,11 @@ When this message is processed the following actions occur: The `MsgCancelUnbondingDelegation` message allows delegators to cancel the `unbondingDelegation` entry and delegate back to a previous validator. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L38-L42 ``` -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L160-L175 ``` @@ -654,27 +662,27 @@ This message is expected to fail if: When this message is processed the following actions occur: * if the `unbondingDelegation` Entry balance is zero - * in this condition `unbondingDelegation` entry will be removed from `unbondingDelegationQueue`. - * otherwise `unbondingDelegationQueue` will be updated with new `unbondingDelegation` entry balance and initial balance + * in this condition `unbondingDelegation` entry will be removed from `unbondingDelegationQueue`. + * otherwise `unbondingDelegationQueue` will be updated with new `unbondingDelegation` entry balance and initial balance * the validator's `DelegatorShares` and the delegation's `Shares` are both increased by the message `Amount`. ### MsgBeginRedelegate -The redelegation command allows delegators to instantly switch validators. Once\ -the unbonding period has passed, the redelegation is automatically completed in\ +The redelegation command allows delegators to instantly switch validators. Once +the unbonding period has passed, the redelegation is automatically completed in the EndBlocker. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L30-L32 ``` -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L119-L132 ``` This message returns a response containing the completion time of the redelegation: -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L133-L138 ``` @@ -692,21 +700,22 @@ When this message is processed the following actions occur: * the source validator's `DelegatorShares` and the delegations `Shares` are both reduced by the message `SharesAmount` * calculate the token worth of the shares remove that amount tokens held within the source validator. * if the source validator is: - * `Bonded` - add an entry to the `Redelegation` (create `Redelegation` if it doesn't exist) with a completion time a full unbonding period from the current time. Update pool shares to reduce BondedTokens and increase NotBondedTokens by token worth of the shares (this may be effectively reversed in the next step however). - * `Unbonding` - add an entry to the `Redelegation` (create `Redelegation` if it doesn't exist) with the same completion time as the validator (`UnbondingMinTime`). - * `Unbonded` - no action required in this step + * `Bonded` - add an entry to the `Redelegation` (create `Redelegation` if it doesn't exist) with a completion time a full unbonding period from the current time. Update pool shares to reduce BondedTokens and increase NotBondedTokens by token worth of the shares (this may be effectively reversed in the next step however). + * `Unbonding` - add an entry to the `Redelegation` (create `Redelegation` if it doesn't exist) with the same completion time as the validator (`UnbondingMinTime`). + * `Unbonded` - no action required in this step * Delegate the token worth to the destination validator, possibly moving tokens back to the bonded state. * if there are no more `Shares` in the source delegation, then the source delegation object is removed from the store - * under this situation if the delegation is the validator's self-delegation then also jail the validator. + * under this situation if the delegation is the validator's self-delegation then also jail the validator. ![Begin redelegation sequence](https://raw.githubusercontent.com/cosmos/cosmos-sdk/release/v0.46.x/docs/uml/svg/begin_redelegation_sequence.svg) + ### MsgUpdateParams -The `MsgUpdateParams` update the staking module parameters.\ +The `MsgUpdateParams` update the staking module parameters. The params are updated through a governance proposal where the signer is the gov module account address. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L182-L195 ``` @@ -716,119 +725,125 @@ The message handling can fail if: ## Begin-Block -Each abci begin block call, the historical info will get stored and pruned\ +Each abci begin block call, the historical info will get stored and pruned according to the `HistoricalEntries` parameter. ### Historical Info Tracking If the `HistoricalEntries` parameter is 0, then the `BeginBlock` performs a no-op. -Otherwise, the latest historical info is stored under the key `historicalInfoKey|height`, while any entries older than `height - HistoricalEntries` is deleted.\ -In most cases, this results in a single entry being pruned per block.\ +Otherwise, the latest historical info is stored under the key `historicalInfoKey|height`, while any entries older than `height - HistoricalEntries` is deleted. +In most cases, this results in a single entry being pruned per block. However, if the parameter `HistoricalEntries` has changed to a lower value there will be multiple entries in the store that must be pruned. ## End-Block -Each abci end block call, the operations to update queues and validator set\ +Each abci end block call, the operations to update queues and validator set changes are specified to execute. ### Validator Set Changes -The staking validator set is updated during this process by state transitions\ -that run at the end of every block. As a part of this process any updated\ -validators are also returned back to CometBFT for inclusion in the CometBFT\ -validator set which is responsible for validating CometBFT messages at the\ +The staking validator set is updated during this process by state transitions +that run at the end of every block. As a part of this process any updated +validators are also returned back to CometBFT for inclusion in the CometBFT +validator set which is responsible for validating CometBFT messages at the consensus layer. Operations are as following: -* the new validator set is taken as the top `params.MaxValidators` number of\ +* the new validator set is taken as the top `params.MaxValidators` number of validators retrieved from the `ValidatorsByPower` index * the previous validator set is compared with the new validator set: - * missing validators begin unbonding and their `Tokens` are transferred from the`BondedPool` to the `NotBondedPool` `ModuleAccount` - * new validators are instantly bonded and their `Tokens` are transferred from the`NotBondedPool` to the `BondedPool` `ModuleAccount` + * missing validators begin unbonding and their `Tokens` are transferred from the + `BondedPool` to the `NotBondedPool` `ModuleAccount` + * new validators are instantly bonded and their `Tokens` are transferred from the + `NotBondedPool` to the `BondedPool` `ModuleAccount` -In all cases, any validators leaving or entering the bonded validator set or\ -changing balances and staying within the bonded validator set incur an update\ +In all cases, any validators leaving or entering the bonded validator set or +changing balances and staying within the bonded validator set incur an update message reporting their new consensus power which is passed back to CometBFT. -The `LastTotalPower` and `LastValidatorsPower` hold the state of the total power\ -and validator power from the end of the last block, and are used to check for\ -changes that have occurred in `ValidatorsByPower` and the total new power, which\ +The `LastTotalPower` and `LastValidatorsPower` hold the state of the total power +and validator power from the end of the last block, and are used to check for +changes that have occurred in `ValidatorsByPower` and the total new power, which is calculated during `EndBlock`. ### Queues -Within staking, certain state-transitions are not instantaneous but take place\ -over a duration of time (typically the unbonding period). When these\ -transitions are mature certain operations must take place in order to complete\ -the state operation. This is achieved through the use of queues which are\ +Within staking, certain state-transitions are not instantaneous but take place +over a duration of time (typically the unbonding period). When these +transitions are mature certain operations must take place in order to complete +the state operation. This is achieved through the use of queues which are checked/processed at the end of each block. #### Unbonding Validators -When a validator is kicked out of the bonded validator set (either through\ -being jailed, or not having sufficient bonded tokens) it begins the unbonding\ -process along with all its delegations begin unbonding (while still being\ -delegated to this validator). At this point the validator is said to be an\ -"unbonding validator", whereby it will mature to become an "unbonded validator"\ +When a validator is kicked out of the bonded validator set (either through +being jailed, or not having sufficient bonded tokens) it begins the unbonding +process along with all its delegations begin unbonding (while still being +delegated to this validator). At this point the validator is said to be an +"unbonding validator", whereby it will mature to become an "unbonded validator" after the unbonding period has passed. -Each block the validator queue is to be checked for mature unbonding validators\ -(namely with a completion time ≤ current time and completion height ≤ current\ -block height). At this point any mature validators which do not have any\ -delegations remaining are deleted from state. For all other mature unbonding\ -validators that still have remaining delegations, the `validator.Status` is\ -switched from `types.Unbonding` to`types.Unbonded`. +Each block the validator queue is to be checked for mature unbonding validators +(namely with a completion time ≤ current time and completion height ≤ current +block height). At this point any mature validators which do not have any +delegations remaining are deleted from state. For all other mature unbonding +validators that still have remaining delegations, the `validator.Status` is +switched from `types.Unbonding` to +`types.Unbonded`. -Unbonding operations can be put on hold by external modules via the `PutUnbondingOnHold(unbondingId)` method.\ -As a result, an unbonding operation (e.g., an unbonding delegation) that is on hold, cannot complete\ -even if it reaches maturity. For an unbonding operation with `unbondingId` to eventually complete\ -(after it reaches maturity), every call to `PutUnbondingOnHold(unbondingId)` must be matched\ -by a call to `UnbondingCanComplete(unbondingId)`. +Unbonding operations can be put on hold by external modules via the `PutUnbondingOnHold(unbondingId)` method. + As a result, an unbonding operation (e.g., an unbonding delegation) that is on hold, cannot complete + even if it reaches maturity. For an unbonding operation with `unbondingId` to eventually complete + (after it reaches maturity), every call to `PutUnbondingOnHold(unbondingId)` must be matched + by a call to `UnbondingCanComplete(unbondingId)`. #### Unbonding Delegations -Complete the unbonding of all mature `UnbondingDelegations.Entries` within the`UnbondingDelegations` queue with the following procedure: +Complete the unbonding of all mature `UnbondingDelegations.Entries` within the +`UnbondingDelegations` queue with the following procedure: * transfer the balance coins to the delegator's wallet address * remove the mature entry from `UnbondingDelegation.Entries` -* remove the `UnbondingDelegation` object from the store if there are no\ +* remove the `UnbondingDelegation` object from the store if there are no remaining entries. #### Redelegations -Complete the unbonding of all mature `Redelegation.Entries` within the`Redelegations` queue with the following procedure: +Complete the unbonding of all mature `Redelegation.Entries` within the +`Redelegations` queue with the following procedure: * remove the mature entry from `Redelegation.Entries` -* remove the `Redelegation` object from the store if there are no\ +* remove the `Redelegation` object from the store if there are no remaining entries. ## Hooks -Other modules may register operations to execute when a certain event has\ -occurred within staking. These events can be registered to execute either\ -right `Before` or `After` the staking event (as per the hook name). The\ +Other modules may register operations to execute when a certain event has +occurred within staking. These events can be registered to execute either +right `Before` or `After` the staking event (as per the hook name). The following hooks can registered with staking: * `AfterValidatorCreated(Context, ValAddress) error` - * called when a validator is created + * called when a validator is created * `BeforeValidatorModified(Context, ValAddress) error` - * called when a validator's state is changed + * called when a validator's state is changed * `AfterValidatorRemoved(Context, ConsAddress, ValAddress) error` - * called when a validator is deleted + * called when a validator is deleted * `AfterValidatorBonded(Context, ConsAddress, ValAddress) error` - * called when a validator is bonded + * called when a validator is bonded * `AfterValidatorBeginUnbonding(Context, ConsAddress, ValAddress) error` - * called when a validator begins unbonding + * called when a validator begins unbonding * `BeforeDelegationCreated(Context, AccAddress, ValAddress) error` - * called when a delegation is created + * called when a delegation is created * `BeforeDelegationSharesModified(Context, AccAddress, ValAddress) error` - * called when a delegation's shares are modified + * called when a delegation's shares are modified * `AfterDelegationModified(Context, AccAddress, ValAddress) error` - * called when a delegation is created or modified + * called when a delegation is created or modified * `BeforeDelegationRemoved(Context, AccAddress, ValAddress) error` - * called when a delegation is removed + * called when a delegation is removed * `AfterUnbondingInitiated(Context, UnbondingID)` - * called when an unbonding operation (validator unbonding, unbonding delegation, redelegation) was initiated + * called when an unbonding operation (validator unbonding, unbonding delegation, redelegation) was initiated + ## Events @@ -836,37 +851,37 @@ The staking module emits the following events: ### EndBlocker -| Type | Attribute Key | Attribute Value | -| ---------------------- | ---------------------- | ------------------------- | -| complete\_unbonding | amount | {totalUnbondingAmount} | -| complete\_unbonding | validator | {validatorAddress} | -| complete\_unbonding | delegator | {delegatorAddress} | -| complete\_redelegation | amount | {totalRedelegationAmount} | -| complete\_redelegation | source\_validator | {srcValidatorAddress} | -| complete\_redelegation | destination\_validator | {dstValidatorAddress} | -| complete\_redelegation | delegator | {delegatorAddress} | +| Type | Attribute Key | Attribute Value | +| --------------------- | --------------------- | ------------------------- | +| complete_unbonding | amount | {totalUnbondingAmount} | +| complete_unbonding | validator | {validatorAddress} | +| complete_unbonding | delegator | {delegatorAddress} | +| complete_redelegation | amount | {totalRedelegationAmount} | +| complete_redelegation | source_validator | {srcValidatorAddress} | +| complete_redelegation | destination_validator | {dstValidatorAddress} | +| complete_redelegation | delegator | {delegatorAddress} | ## Msg's ### MsgCreateValidator -| Type | Attribute Key | Attribute Value | -| ----------------- | ------------- | ------------------ | -| create\_validator | validator | {validatorAddress} | -| create\_validator | amount | {delegationAmount} | -| message | module | staking | -| message | action | create\_validator | -| message | sender | {senderAddress} | +| Type | Attribute Key | Attribute Value | +| ---------------- | ------------- | ------------------ | +| create_validator | validator | {validatorAddress} | +| create_validator | amount | {delegationAmount} | +| message | module | staking | +| message | action | create_validator | +| message | sender | {senderAddress} | ### MsgEditValidator -| Type | Attribute Key | Attribute Value | -| --------------- | --------------------- | ------------------- | -| edit\_validator | commission\_rate | {commissionRate} | -| edit\_validator | min\_self\_delegation | {minSelfDelegation} | -| message | module | staking | -| message | action | edit\_validator | -| message | sender | {senderAddress} | +| Type | Attribute Key | Attribute Value | +| -------------- | ------------------- | ------------------- | +| edit_validator | commission_rate | {commissionRate} | +| edit_validator | min_self_delegation | {minSelfDelegation} | +| message | module | staking | +| message | action | edit_validator | +| message | sender | {senderAddress} | ### MsgDelegate @@ -880,49 +895,49 @@ The staking module emits the following events: ### MsgUndelegate -| Type | Attribute Key | Attribute Value | -| ------- | --------------------- | ------------------ | -| unbond | validator | {validatorAddress} | -| unbond | amount | {unbondAmount} | -| unbond | completion\_time \[0] | {completionTime} | -| message | module | staking | -| message | action | begin\_unbonding | -| message | sender | {senderAddress} | +| Type | Attribute Key | Attribute Value | +| ------- | ------------------- | ------------------ | +| unbond | validator | {validatorAddress} | +| unbond | amount | {unbondAmount} | +| unbond | completion_time [0] | {completionTime} | +| message | module | staking | +| message | action | begin_unbonding | +| message | sender | {senderAddress} | -* \[0] Time is formatted in the RFC3339 standard +* [0] Time is formatted in the RFC3339 standard ### MsgCancelUnbondingDelegation -| Type | Attribute Key | Attribute Value | -| ----------------------------- | ---------------- | --------------------------------- | -| cancel\_unbonding\_delegation | validator | {validatorAddress} | -| cancel\_unbonding\_delegation | delegator | {delegatorAddress} | -| cancel\_unbonding\_delegation | amount | {cancelUnbondingDelegationAmount} | -| cancel\_unbonding\_delegation | creation\_height | {unbondingCreationHeight} | -| message | module | staking | -| message | action | cancel\_unbond | -| message | sender | {senderAddress} | +| Type | Attribute Key | Attribute Value | +| ----------------------------- | ------------------ | ------------------------------------| +| cancel_unbonding_delegation | validator | {validatorAddress} | +| cancel_unbonding_delegation | delegator | {delegatorAddress} | +| cancel_unbonding_delegation | amount | {cancelUnbondingDelegationAmount} | +| cancel_unbonding_delegation | creation_height | {unbondingCreationHeight} | +| message | module | staking | +| message | action | cancel_unbond | +| message | sender | {senderAddress} | ### MsgBeginRedelegate -| Type | Attribute Key | Attribute Value | -| ---------- | ---------------------- | --------------------- | -| redelegate | source\_validator | {srcValidatorAddress} | -| redelegate | destination\_validator | {dstValidatorAddress} | -| redelegate | amount | {unbondAmount} | -| redelegate | completion\_time \[0] | {completionTime} | -| message | module | staking | -| message | action | begin\_redelegate | -| message | sender | {senderAddress} | +| Type | Attribute Key | Attribute Value | +| ---------- | --------------------- | --------------------- | +| redelegate | source_validator | {srcValidatorAddress} | +| redelegate | destination_validator | {dstValidatorAddress} | +| redelegate | amount | {unbondAmount} | +| redelegate | completion_time [0] | {completionTime} | +| message | module | staking | +| message | action | begin_redelegate | +| message | sender | {senderAddress} | -* \[0] Time is formatted in the RFC3339 standard +* [0] Time is formatted in the RFC3339 standard ## Parameters The staking module contains the following parameters: | Key | Type | Example | -| ----------------- | ---------------- | ---------------------- | +|-------------------|------------------|------------------------| | UnbondingTime | string (time ns) | "259200000000000" | | MaxValidators | uint16 | 100 | | KeyMaxEntries | uint16 | 7 | @@ -944,7 +959,7 @@ The `query` commands allows users to query `staking` state. simd query staking --help ``` -**delegation** +##### delegation The `delegation` command allows users to query delegations for an individual delegator on an individual validator. @@ -972,7 +987,7 @@ delegation: validator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj ``` -**delegations** +##### delegations The `delegations` command allows users to query delegations for an individual delegator on all validators. @@ -1011,7 +1026,7 @@ pagination: total: "0" ``` -**delegations-to** +##### delegations-to The `delegations-to` command allows users to query delegations on an individual validator. @@ -1049,7 +1064,7 @@ pagination: total: "0" ``` -**historical-info** +##### historical-info The `historical-info` command allows users to query historical information at given height. @@ -1115,7 +1130,7 @@ valset: unbonding_time: "1970-01-01T00:00:00Z" ``` -**params** +##### params The `params` command allows users to query values set as staking parameters. @@ -1141,7 +1156,7 @@ max_validators: 50 unbonding_time: 1814400s ``` -**pool** +##### pool The `pool` command allows users to query values for amounts stored in the staking pool. @@ -1164,7 +1179,7 @@ bonded_tokens: "10000000" not_bonded_tokens: "0" ``` -**redelegation** +##### redelegation The `redelegation` command allows users to query a redelegation record based on delegator and a source and destination validator address. @@ -1205,7 +1220,7 @@ redelegation_responses: validator_src_address: cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm ``` -**redelegations** +##### redelegations The `redelegations` command allows users to query all redelegation records for an individual delegator. @@ -1260,7 +1275,7 @@ redelegation_responses: validator_src_address: cosmosvaloper1zppjyal5emta5cquje8ndkpz0rs046m7zqxrpp ``` -**redelegations-from** +##### redelegations-from The `redelegations-from` command allows users to query delegations that are redelegating _from_ a validator. @@ -1315,7 +1330,7 @@ redelegation_responses: validator_src_address: cosmosvaloper1y4rzzrgl66eyhzt6gse2k7ej3zgwmngeleucjy ``` -**unbonding-delegation** +##### unbonding-delegation The `unbonding-delegation` command allows users to query unbonding delegations for an individual delegator on an individual validator. @@ -1343,7 +1358,7 @@ entries: validator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj ``` -**unbonding-delegations** +##### unbonding-delegations The `unbonding-delegations` command allows users to query all unbonding-delegations records for one delegator. @@ -1376,7 +1391,7 @@ unbonding_responses: ``` -**unbonding-delegations-from** +##### unbonding-delegations-from The `unbonding-delegations-from` command allows users to query delegations that are unbonding _from_ a validator. @@ -1415,7 +1430,7 @@ unbonding_responses: validator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj ``` -**validator** +##### validator The `validator` command allows users to query details about an individual validator. @@ -1462,7 +1477,7 @@ unbonding_height: "0" unbonding_time: "1970-01-01T00:00:00Z" ``` -**validators** +##### validators The `validators` command allows users to query details about all validators on a network. @@ -1547,7 +1562,7 @@ The `tx` commands allows users to interact with the `staking` module. simd tx staking --help ``` -**create-validator** +##### create-validator The command `create-validator` allows users to create new validator initialized with a self-delegation to it. @@ -1587,7 +1602,7 @@ where `validator.json` contains: and pubkey can be obtained by using `simd tendermint show-validator` command. -**delegate** +##### delegate The command `delegate` allows users to delegate liquid tokens to a validator. @@ -1603,7 +1618,7 @@ Example: simd tx staking delegate cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 1000stake --from mykey ``` -**edit-validator** +##### edit-validator The command `edit-validator` allows users to edit an existing validator account. @@ -1619,7 +1634,7 @@ Example: simd tx staking edit-validator --moniker "new_moniker_name" --website "new_webiste_url" --from mykey ``` -**redelegate** +##### redelegate The command `redelegate` allows users to redelegate illiquid tokens from one validator to another. @@ -1635,7 +1650,7 @@ Example: simd tx staking redelegate cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 100stake --from mykey ``` -**unbond** +##### unbond The command `unbond` allows users to unbond shares from a validator. @@ -1651,7 +1666,7 @@ Example: simd tx staking unbond cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 100stake --from mykey ``` -**cancel unbond** +##### cancel unbond The command `cancel-unbond` allow users to cancel the unbonding delegation entry and delegate back to the original validator. @@ -1667,6 +1682,7 @@ Example: simd tx staking cancel-unbond cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 100stake 123123 --from mykey ``` + ### gRPC A user can query the `staking` module using gRPC endpoints. diff --git a/.gitbook/developers-native/core/upgrade.mdx b/.gitbook/developers-native/core/upgrade/index.md similarity index 84% rename from .gitbook/developers-native/core/upgrade.mdx rename to .gitbook/developers-native/core/upgrade/index.md index dfe8ff5..0d98c16 100644 --- a/.gitbook/developers-native/core/upgrade.mdx +++ b/.gitbook/developers-native/core/upgrade/index.md @@ -2,42 +2,43 @@ sidebar_position: 1 --- -# Upgrade +# `x/upgrade` ## Abstract -`x/upgrade` is an implementation of a Cosmos SDK module that facilitates smoothly\ -upgrading a live Cosmos chain to a new (breaking) software version. It accomplishes this by\ -providing a `PreBlocker` hook that prevents the blockchain state machine from\ +`x/upgrade` is an implementation of a Cosmos SDK module that facilitates smoothly +upgrading a live Cosmos chain to a new (breaking) software version. It accomplishes this by +providing a `PreBlocker` hook that prevents the blockchain state machine from proceeding once a pre-defined upgrade block height has been reached. -The module does not prescribe anything regarding how governance decides to do an\ -upgrade, but just the mechanism for coordinating the upgrade safely. Without software\ -support for upgrades, upgrading a live chain is risky because all of the validators\ -need to pause their state machines at exactly the same point in the process. If\ -this is not done correctly, there can be state inconsistencies which are hard to\ +The module does not prescribe anything regarding how governance decides to do an +upgrade, but just the mechanism for coordinating the upgrade safely. Without software +support for upgrades, upgrading a live chain is risky because all of the validators +need to pause their state machines at exactly the same point in the process. If +this is not done correctly, there can be state inconsistencies which are hard to recover from. -* [Concepts](./#concepts) -* [State](./#state) -* [Events](./#events) -* [Client](./#client) - * [CLI](./#cli) - * [REST](./#rest) - * [gRPC](./#grpc) -* [Resources](./#resources) +* [Concepts](#concepts) +* [State](#state) +* [Events](#events) +* [Client](#client) + * [CLI](#cli) + * [REST](#rest) + * [gRPC](#grpc) +* [Resources](#resources) ## Concepts ### Plan -The `x/upgrade` module defines a `Plan` type in which a live upgrade is scheduled\ -to occur. A `Plan` can be scheduled at a specific block height.\ -A `Plan` is created once a (frozen) release candidate along with an appropriate upgrade`Handler` (see below) is agreed upon, where the `Name` of a `Plan` corresponds to a\ -specific `Handler`. Typically, a `Plan` is created through a governance proposal\ -process, where if voted upon and passed, will be scheduled. The `Info` of a `Plan`\ -may contain various metadata about the upgrade, typically application specific\ -upgrade info to be included on-chain such as a git commit that validators could\ +The `x/upgrade` module defines a `Plan` type in which a live upgrade is scheduled +to occur. A `Plan` can be scheduled at a specific block height. +A `Plan` is created once a (frozen) release candidate along with an appropriate upgrade +`Handler` (see below) is agreed upon, where the `Name` of a `Plan` corresponds to a +specific `Handler`. Typically, a `Plan` is created through a governance proposal +process, where if voted upon and passed, will be scheduled. The `Info` of a `Plan` +may contain various metadata about the upgrade, typically application specific +upgrade info to be included on-chain such as a git commit that validators could automatically upgrade to. ```go @@ -50,31 +51,37 @@ type Plan struct { #### Sidecar Process -If an operator running the application binary also runs a sidecar process to assist\ -in the automatic download and upgrade of a binary, the `Info` allows this process to\ +If an operator running the application binary also runs a sidecar process to assist +in the automatic download and upgrade of a binary, the `Info` allows this process to be seamless. This tool is [Cosmovisor](https://github.com/cosmos/cosmos-sdk/tree/main/tools/cosmovisor#readme). ### Handler -The `x/upgrade` module facilitates upgrading from major version X to major version Y. To\ -accomplish this, node operators must first upgrade their current binary to a new\ -binary that has a corresponding `Handler` for the new version Y. It is assumed that\ -this version has fully been tested and approved by the community at large. This`Handler` defines what state migrations need to occur before the new binary Y\ -can successfully run the chain. Naturally, this `Handler` is application specific\ -and not defined on a per-module basis. Registering a `Handler` is done via`Keeper#SetUpgradeHandler` in the application. +The `x/upgrade` module facilitates upgrading from major version X to major version Y. To +accomplish this, node operators must first upgrade their current binary to a new +binary that has a corresponding `Handler` for the new version Y. It is assumed that +this version has fully been tested and approved by the community at large. This +`Handler` defines what state migrations need to occur before the new binary Y +can successfully run the chain. Naturally, this `Handler` is application specific +and not defined on a per-module basis. Registering a `Handler` is done via +`Keeper#SetUpgradeHandler` in the application. ```go type UpgradeHandler func(Context, Plan, VersionMap) (VersionMap, error) ``` -During each `EndBlock` execution, the `x/upgrade` module checks if there exists a`Plan` that should execute (is scheduled at that height). If so, the corresponding`Handler` is executed. If the `Plan` is expected to execute but no `Handler` is registered\ +During each `EndBlock` execution, the `x/upgrade` module checks if there exists a +`Plan` that should execute (is scheduled at that height). If so, the corresponding +`Handler` is executed. If the `Plan` is expected to execute but no `Handler` is registered or if the binary was upgraded too early, the node will gracefully panic and exit. ### StoreLoader -The `x/upgrade` module also facilitates store migrations as part of the upgrade. The`StoreLoader` sets the migrations that need to occur before the new binary can\ -successfully run the chain. This `StoreLoader` is also application specific and\ -not defined on a per-module basis. Registering this `StoreLoader` is done via`app#SetStoreLoader` in the application. +The `x/upgrade` module also facilitates store migrations as part of the upgrade. The +`StoreLoader` sets the migrations that need to occur before the new binary can +successfully run the chain. This `StoreLoader` is also application specific and +not defined on a per-module basis. Registering this `StoreLoader` is done via +`app#SetStoreLoader` in the application. ```go func UpgradeStoreLoader (upgradeHeight int64, storeUpgrades *store.StoreUpgrades) baseapp.StoreLoader @@ -82,60 +89,64 @@ func UpgradeStoreLoader (upgradeHeight int64, storeUpgrades *store.StoreUpgrades If there's a planned upgrade and the upgrade height is reached, the old binary writes `Plan` to the disk before panicking. -This information is critical to ensure the `StoreUpgrades` happens smoothly at correct height and\ -expected upgrade. It eliminiates the chances for the new binary to execute `StoreUpgrades` multiple\ -times everytime on restart. Also if there are multiple upgrades planned on same height, the `Name`\ +This information is critical to ensure the `StoreUpgrades` happens smoothly at correct height and +expected upgrade. It eliminiates the chances for the new binary to execute `StoreUpgrades` multiple +times everytime on restart. Also if there are multiple upgrades planned on same height, the `Name` will ensure these `StoreUpgrades` takes place only in planned upgrade handler. ### Proposal -Typically, a `Plan` is proposed and submitted through governance via a proposal\ -containing a `MsgSoftwareUpgrade` message.\ -This proposal prescribes to the standard governance process. If the proposal passes,\ -the `Plan`, which targets a specific `Handler`, is persisted and scheduled. The\ +Typically, a `Plan` is proposed and submitted through governance via a proposal +containing a `MsgSoftwareUpgrade` message. +This proposal prescribes to the standard governance process. If the proposal passes, +the `Plan`, which targets a specific `Handler`, is persisted and scheduled. The upgrade can be delayed or hastened by updating the `Plan.Height` in a new proposal. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/upgrade/v1beta1/tx.proto#L29-L41 ``` #### Cancelling Upgrade Proposals -Upgrade proposals can be cancelled. There exists a gov-enabled `MsgCancelUpgrade`\ -message type, which can be embedded in a proposal, voted on and, if passed, will\ -remove the scheduled upgrade `Plan`.\ -Of course this requires that the upgrade was known to be a bad idea well before the\ +Upgrade proposals can be cancelled. There exists a gov-enabled `MsgCancelUpgrade` +message type, which can be embedded in a proposal, voted on and, if passed, will +remove the scheduled upgrade `Plan`. +Of course this requires that the upgrade was known to be a bad idea well before the upgrade itself, to allow time for a vote. -```protobuf +```protobuf reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/upgrade/v1beta1/tx.proto#L48-L57 ``` -If such a possibility is desired, the upgrade height is to be`2 * (VotingPeriod + DepositPeriod) + (SafetyDelta)` from the beginning of the\ -upgrade proposal. The `SafetyDelta` is the time available from the success of an\ +If such a possibility is desired, the upgrade height is to be +`2 * (VotingPeriod + DepositPeriod) + (SafetyDelta)` from the beginning of the +upgrade proposal. The `SafetyDelta` is the time available from the success of an upgrade proposal and the realization it was a bad idea (due to external social consensus). -A `MsgCancelUpgrade` proposal can also be made while the original`MsgSoftwareUpgrade` proposal is still being voted upon, as long as the `VotingPeriod`\ +A `MsgCancelUpgrade` proposal can also be made while the original +`MsgSoftwareUpgrade` proposal is still being voted upon, as long as the `VotingPeriod` ends after the `MsgSoftwareUpgrade` proposal. ## State -The internal state of the `x/upgrade` module is relatively minimal and simple. The\ -state contains the currently active upgrade `Plan` (if one exists) by key`0x0` and if a `Plan` is marked as "done" by key `0x1`. The state\ -contains the consensus versions of all app modules in the application. The versions\ -are stored as big endian `uint64`, and can be accessed with prefix `0x2` appended\ -by the corresponding module name of type `string`. The state maintains a`Protocol Version` which can be accessed by key `0x3`. +The internal state of the `x/upgrade` module is relatively minimal and simple. The +state contains the currently active upgrade `Plan` (if one exists) by key +`0x0` and if a `Plan` is marked as "done" by key `0x1`. The state +contains the consensus versions of all app modules in the application. The versions +are stored as big endian `uint64`, and can be accessed with prefix `0x2` appended +by the corresponding module name of type `string`. The state maintains a +`Protocol Version` which can be accessed by key `0x3`. * Plan: `0x0 -> Plan` -* Done: `0x1 | byte(plan name) -> BigEndian(Block Height)` -* ConsensusVersion: `0x2 | byte(module name) -> BigEndian(Module Consensus Version)` +* Done: `0x1 | byte(plan name) -> BigEndian(Block Height)` +* ConsensusVersion: `0x2 | byte(module name) -> BigEndian(Module Consensus Version)` * ProtocolVersion: `0x3 -> BigEndian(Protocol Version)` The `x/upgrade` module contains no genesis state. ## Events -The `x/upgrade` does not emit any events by itself. Any and all proposal related\ +The `x/upgrade` does not emit any events by itself. Any and all proposal related events are emitted through the `x/gov` module. ## Client @@ -152,7 +163,7 @@ The `query` commands allow users to query `upgrade` state. simd query upgrade --help ``` -**applied** +##### applied The `applied` command allows users to query the block header for height at which a completed upgrade was applied. @@ -160,7 +171,7 @@ The `applied` command allows users to query the block header for height at which simd query upgrade applied [upgrade-name] [flags] ``` -If upgrade-name was previously executed on the chain, this returns the header for the block at which it was applied.\ +If upgrade-name was previously executed on the chain, this returns the header for the block at which it was applied. This helps a client determine which binary was valid over a given range of blocks, as well as more context to understand past migrations. Example: @@ -208,11 +219,11 @@ Example Output: } ``` -**module versions** +##### module versions The `module_versions` command gets a list of module names and their respective consensus versions. -Following the command with a specific module name will return only\ +Following the command with a specific module name will return only that module's information. ```bash @@ -279,7 +290,7 @@ module_versions: version: "2" ``` -**plan** +##### plan The `plan` command gets the currently scheduled upgrade plan, if one exists. diff --git a/.gitbook/developers-native/examples.mdx b/.gitbook/developers-native/examples.mdx index 9b1053f..53e5e23 100644 --- a/.gitbook/developers-native/examples.mdx +++ b/.gitbook/developers-native/examples.mdx @@ -1,4 +1,6 @@ -# Core Modules +--- +title: Core Modules +--- Within this section, we are going to explore the core modules of the Injective chain and provide examples of how to make and broadcast transactions for each of the Messages defined on-chain. @@ -6,17 +8,17 @@ Within this section, we are going to explore the core modules of the Injective c | Topic | Description | | -------------------------------- | ---------------------------------------------------- | -| [Auction](auction.md) | Used for the buy-back-and-burn on chain mechanism | -| [AuthZ](authz.md) | Used for granting account priveledges | -| [Bank](bank.md) | Used for managing users assets (funds) | -| [Distribution](distribution.md) | Used for on-chain distribution/minting | -| [Exchange](exchange.md) | Used for the exchange primitives | -| [Feegrant](feegrant.md) | Used for granting fee allowance priveledges | -| [Governance](governance.md) | Used for on-chain governance | -| [IBC](ibc.md) | Used for cross-Cosmos chain transfers | -| [Insurance](insurance.md) | Used for on-chain insurance funds | -| [Peggy](peggy.md) | Used for the Injective ↔ Ethereum Bridge | -| [Permissions](permissions.md) | Used fot on-chain permissions -| [Staking](staking.md) | Used for on-chain staking | -| [Tokenfactory](token-factory.md) | Used for creating and managing `tokenfactory` tokens | -| [Wasm](wasm.md) | Used for interacting with the Cosmwasm Layer | +| [Auction](./examples/auction/) | Used for the buy-back-and-burn on chain mechanism | +| [AuthZ](./examples/authz/) | Used for granting account priveledges | +| [Bank](./examples/bank/) | Used for managing users assets (funds) | +| [Distribution](./examples/distribution/) | Used for on-chain distribution/minting | +| [Exchange](./examples/exchange/) | Used for the exchange primitives | +| [Feegrant](./examples/feegrant/) | Used for granting fee allowance priveledges | +| [Governance](./examples/governance/) | Used for on-chain governance | +| [IBC](./examples/ibc/) | Used for cross-Cosmos chain transfers | +| [Insurance](./examples/insurance/) | Used for on-chain insurance funds | +| [Peggy](./examples/peggy/) | Used for the Injective ↔ Ethereum Bridge | +| [Permissions](./examples/permissions/) | Used fot on-chain permissions +| [Staking](./examples/staking/) | Used for on-chain staking | +| [Tokenfactory](./examples/token-factory/) | Used for creating and managing `tokenfactory` tokens | +| [Wasm](./examples/wasm/) | Used for interacting with the Cosmwasm Layer | diff --git a/.gitbook/developers-native/examples/auction.mdx b/.gitbook/developers-native/examples/auction.mdx index de01094..1ea43a6 100644 --- a/.gitbook/developers-native/examples/auction.mdx +++ b/.gitbook/developers-native/examples/auction.mdx @@ -1,4 +1,6 @@ -# Auction +--- +title: Auction +--- The `auction` module is heart of the `buy-back-and-burn` on chain mechanism, where 60% of the weekly trading fees are collected and auctioned off to the highest INJ bidder where the submitted INJ of the highest bidder are burned in the process. @@ -61,12 +63,12 @@ Notes: How to find the subaccountId that you will be transferring from: -- you can query your existing subaccountIds via the [account portfolio api](../query-indexer/portfolio.md). +- you can query your existing subaccountIds via the [account portfolio api](../query-indexer/portfolio/). How to use funds that are currently associated with your Injective Address in bank module: -- If you have existing non-default subaccounts, you'll want to do a[ MsgDeposit ](exchange.md#msgdeposit)to one of your existing non-default subaccountIds and use that subaccountId as the `srcSubaccountId` below. -- If you don't have existing non-default subaccounts, you can do a [MsgDeposit](exchange.md#msgdeposit) to a new default subaccountId, which would be done via importing `getSubaccountId` from `sdk-ts` and setting the `subaccountId` field in [MsgDeposit](exchange.md#msgdeposit) to `getSubaccountId(injectiveAddress, 1)`. +- If you have existing non-default subaccounts, you'll want to do a [MsgDeposit](./exchange/#msgdeposit)to one of your existing non-default subaccountIds and use that subaccountId as the `srcSubaccountId` below. +- If you don't have existing non-default subaccounts, you can do a [MsgDeposit](./exchange/#msgdeposit) to a new default subaccountId, which would be done via importing `getSubaccountId` from `sdk-ts` and setting the `subaccountId` field in [MsgDeposit](./exchange/#msgdeposit) to `getSubaccountId(injectiveAddress, 1)`. For more info, check out the [burn auction pool docs](https://docs.injective.network/developers/modules/injective/auction). diff --git a/.gitbook/developers-native/examples/authz.mdx b/.gitbook/developers-native/examples/authz.mdx index b84c94e..78cae8a 100644 --- a/.gitbook/developers-native/examples/authz.mdx +++ b/.gitbook/developers-native/examples/authz.mdx @@ -1,4 +1,6 @@ -# AuthZ +--- +title: AuthZ +--- The `authz` module is an implementation of a Cosmos SDK module, per ADR 30, that allows granting arbitrary privileges from one account (the granter) to another account (the grantee). diff --git a/.gitbook/developers-native/examples/bank.mdx b/.gitbook/developers-native/examples/bank.mdx index f811468..e10ae7b 100644 --- a/.gitbook/developers-native/examples/bank.mdx +++ b/.gitbook/developers-native/examples/bank.mdx @@ -1,4 +1,6 @@ -# Bank +--- +title: Bank +--- The bank module is responsible for handling multi-asset coin transfers between accounts and tracking special-case pseudo-transfers which must work differently with particular kinds of accounts (notably delegating/undelegating for vesting accounts). It exposes several interfaces with varying capabilities for secure interaction with other modules which must alter user balances. @@ -10,7 +12,7 @@ Let's explore (and provide examples) the messages that the Bank module exports a ### MsgSend -This message is used to send coins from one address to another. Any TokenFactory token and Peggy token can be used here. To transfer CW20 tokens, see the `MsgExecuteContract` section in [wasm module examples](../../developers-native/examples/wasm.md#msgexecutecontract-transfer). +This message is used to send coins from one address to another. Any TokenFactory token and Peggy token can be used here. To transfer CW20 tokens, see the `MsgExecuteContract` section in [wasm module examples](../../developers-native/examples/wasm/#msgexecutecontract-transfer). ```ts import { MsgSend, MsgBroadcasterWithPk } from '@injectivelabs/sdk-ts' diff --git a/.gitbook/developers-native/examples/distribution.mdx b/.gitbook/developers-native/examples/distribution.mdx index fe50986..088c726 100644 --- a/.gitbook/developers-native/examples/distribution.mdx +++ b/.gitbook/developers-native/examples/distribution.mdx @@ -1,4 +1,6 @@ -# Distribution +--- +title: Distribution +--- The `distribution` module is extended from the cosmos sdk [distribution module](https://github.com/InjectiveLabs/cosmos-sdk/tree/master/x/distribution), where delegator can withdraw their staking rewards from the validator. diff --git a/.gitbook/developers-native/examples/exchange.mdx b/.gitbook/developers-native/examples/exchange.mdx index 545d4a2..26b7f43 100644 --- a/.gitbook/developers-native/examples/exchange.mdx +++ b/.gitbook/developers-native/examples/exchange.mdx @@ -1,4 +1,6 @@ -# Exchange +--- +title: Exchange +--- The `exchange` module is the heart of the Injective Chain which enables fully decentralized spot and derivative exchange. It is the sine qua non module of the chain and integrates tightly with the `auction`, `insurance`, `oracle`, and `peggy` modules. @@ -588,12 +590,12 @@ Note: How to find the subaccountId that you will be transferring from: -* you can query your existing subaccountIds via the [account portfolio api](../query-indexer/portfolio.md). +* you can query your existing subaccountIds via the [account portfolio api](../query-indexer/portfolio/). How to use funds that are currently associated with your Injective Address in bank module: -* If you have existing non-default subaccounts, you'll want to do a [MsgDeposit](exchange.md#MsgDeposit) to one of your existing non-default subaccountIds and use that subaccountId as the `srcSubaccountId` below. -* If you don't have existing non-default subaccounts, you can do a [MsgDeposit](exchange.md#MsgDeposit) to a new default subaccountId, which would be done via importing `getSubaccountId` from `sdk-ts` and setting the `subaccountId` field in [MsgDeposit](exchange.md#MsgDeposit) to `getSubaccountId(injectiveAddress, 1)`. +* If you have existing non-default subaccounts, you'll want to do a [MsgDeposit](./exchange/#MsgDeposit) to one of your existing non-default subaccountIds and use that subaccountId as the `srcSubaccountId` below. +* If you don't have existing non-default subaccounts, you can do a [MsgDeposit](./exchange/#MsgDeposit) to a new default subaccountId, which would be done via importing `getSubaccountId` from `sdk-ts` and setting the `subaccountId` field in [MsgDeposit](./exchange/#MsgDeposit) to `getSubaccountId(injectiveAddress, 1)`. ```ts import { diff --git a/.gitbook/developers-native/examples/feegrant.mdx b/.gitbook/developers-native/examples/feegrant.mdx index c052621..b767280 100644 --- a/.gitbook/developers-native/examples/feegrant.mdx +++ b/.gitbook/developers-native/examples/feegrant.mdx @@ -1,4 +1,6 @@ -# Fee Grant +--- +title: Fee Grant +--- The `feegrant` module allows accounts (granters) to grant fee allowances to other accounts (grantees). This allows the grantee to use the granter's funds to pay for transaction fees. diff --git a/.gitbook/developers-native/examples/governance.mdx b/.gitbook/developers-native/examples/governance.mdx index c64e05f..17b6b7e 100644 --- a/.gitbook/developers-native/examples/governance.mdx +++ b/.gitbook/developers-native/examples/governance.mdx @@ -1,4 +1,6 @@ -# Governance +--- +title: Governance +--- Injective is a community-run blockchain and users who have staked INJ are able to participate in governance as it relates to the blockchain. Proposals can be submitted to make revisions to Injective programs, tech upgrades, or any other Injective related changes that impact the entire Injective ecosystem. diff --git a/.gitbook/developers-native/examples/ibc.mdx b/.gitbook/developers-native/examples/ibc.mdx index 87a73aa..967aada 100644 --- a/.gitbook/developers-native/examples/ibc.mdx +++ b/.gitbook/developers-native/examples/ibc.mdx @@ -1,4 +1,6 @@ -# IBC +--- +title: IBC +--- ## Messages diff --git a/.gitbook/developers-native/examples/insurance.mdx b/.gitbook/developers-native/examples/insurance.mdx index 728e0a8..b3cab51 100644 --- a/.gitbook/developers-native/examples/insurance.mdx +++ b/.gitbook/developers-native/examples/insurance.mdx @@ -1,4 +1,6 @@ -# Insurance +--- +title: Insurance +--- This module provides insurance funds for derivative markets in the exchange module of the Injective Chain to use in order to support higher leverage trading. On a high level, insurance funds for each derivative market are funded by a permissionless group of underwriters who each own a proportional claim (represented through insurance fund share tokens) over the underlying assets in the insurance fund. diff --git a/.gitbook/developers-native/examples/peggy.mdx b/.gitbook/developers-native/examples/peggy.mdx index bc07aeb..9267632 100644 --- a/.gitbook/developers-native/examples/peggy.mdx +++ b/.gitbook/developers-native/examples/peggy.mdx @@ -1,4 +1,6 @@ -# Peggy +--- +title: Peggy +--- The `peggy` module is the heart of the injective ↔ ethereum bridge, where deposited funds will be locked on the ethereum [peggy contract](https://etherscan.io/address/0xF955C57f9EA9Dc8781965FEaE0b6A2acE2BAD6f3#code) and minted on the Injective chain. Similarly withdrawal funds will be burned on the injective chain and unlocked on the ethereum peggy contract. diff --git a/.gitbook/developers-native/examples/permissions.mdx b/.gitbook/developers-native/examples/permissions.mdx index 42467d7..2d5a75a 100644 --- a/.gitbook/developers-native/examples/permissions.mdx +++ b/.gitbook/developers-native/examples/permissions.mdx @@ -1,4 +1,6 @@ -# Permissions +--- +title: Permissions +--- The Permissions Module facilitates the management of namespaces, roles, and permissions within the Injective ecosystem. This documentation outlines the key message types and their usage for interacting with permissions-related data. diff --git a/.gitbook/developers-native/examples/staking.mdx b/.gitbook/developers-native/examples/staking.mdx index e559c36..46845f8 100644 --- a/.gitbook/developers-native/examples/staking.mdx +++ b/.gitbook/developers-native/examples/staking.mdx @@ -1,4 +1,6 @@ -# Staking +--- +title: Staking +--- The module enables Cosmos SDK-based blockchain to support an advanced Proof-of-Stake (PoS) system. In this system, holders of the native staking token of the chain can become validators and can delegate tokens to validators, ultimately determining the effective validator set for the system. diff --git a/.gitbook/developers-native/examples/token-factory.mdx b/.gitbook/developers-native/examples/token-factory.mdx index dedf2f6..c08108a 100644 --- a/.gitbook/developers-native/examples/token-factory.mdx +++ b/.gitbook/developers-native/examples/token-factory.mdx @@ -1,4 +1,6 @@ -# Token Factory +--- +title: Token Factory +--- This `tokenfactory` module allows any account to create a new token with the name `factory/{creator address}/{subdenom}`. Because tokens are namespaced by creator address, this allows token minting to be permissionless, due to not needing to resolve name collisions. diff --git a/.gitbook/developers-native/examples/wasm.mdx b/.gitbook/developers-native/examples/wasm.mdx index 7a96f80..623f8de 100644 --- a/.gitbook/developers-native/examples/wasm.mdx +++ b/.gitbook/developers-native/examples/wasm.mdx @@ -1,4 +1,6 @@ -# Wasm +--- +title: Wasm +--- The `wasm` module is the heart of interacting with the wasm smart contracts deployed on the injective chain, here you can find a list of [smart contracts](https://injscan.com/smart-contracts/) that are deployed on the Injective chain. diff --git a/.gitbook/developers-native.mdx b/.gitbook/developers-native/index.mdx similarity index 75% rename from .gitbook/developers-native.mdx rename to .gitbook/developers-native/index.mdx index 9601962..11beb61 100644 --- a/.gitbook/developers-native.mdx +++ b/.gitbook/developers-native/index.mdx @@ -1,9 +1,7 @@ --- - +title: Native Developers --- -# Native Developers - ## What are Modules?​ Modules are foundational components in Injective’s blockchain architecture, each built to provide specific functionalities. A module is essentially a self-contained unit with well-defined logic and services, allowing Injective to efficiently manage diverse operations across the network. @@ -14,5 +12,23 @@ Modules work like building blocks that can be combined to expand the blockchain ## Explore Modules -
Injectiveinjective
Corecore
- + + + `injective` module + + + `core` module + + diff --git a/.gitbook/developers-native/injective.mdx b/.gitbook/developers-native/injective.mdx index dd7ea83..90c897a 100644 --- a/.gitbook/developers-native/injective.mdx +++ b/.gitbook/developers-native/injective.mdx @@ -1,3 +1,5 @@ -# Injective +--- +title: Injective +--- ## Injective Modules diff --git a/.gitbook/developers-native/injective/auction/01_state.mdx b/.gitbook/developers-native/injective/auction/01_state.md similarity index 100% rename from .gitbook/developers-native/injective/auction/01_state.mdx rename to .gitbook/developers-native/injective/auction/01_state.md diff --git a/.gitbook/developers-native/injective/auction/02_messages.mdx b/.gitbook/developers-native/injective/auction/02_messages.md similarity index 100% rename from .gitbook/developers-native/injective/auction/02_messages.mdx rename to .gitbook/developers-native/injective/auction/02_messages.md diff --git a/.gitbook/developers-native/injective/auction/03_end_block.md b/.gitbook/developers-native/injective/auction/03_end_block.md new file mode 100644 index 0000000..88018bc --- /dev/null +++ b/.gitbook/developers-native/injective/auction/03_end_block.md @@ -0,0 +1,21 @@ +--- +sidebar_position: 3 +title: End-Block +--- + +# End-Block + +### Auction Settlement + +The settlement of a given auction round occurs when `blockTime ≥ EndingTimeStamp.` If a non-zero INJ bid was placed during this period (i.e. there exists a `LastBid`), the following procedure will take place: + +- The winning INJ bid amount is burned. +- The basket of coins held by the auction module is transferred to the winning bidder. +- `LastAuctionResult` is written to state and `EventAuctionResult` is emitted. +- The `LastBid` is cleared. +- The AuctionRound is incremented by 1 and the EndingTimestamp is incremented by `AuctionPeriod`. +- The accumulated exchange fees are transferred from the `exchange` module to the `auction` module for the new upcoming auction. + +If the round closed without any successful bids, the existing coin basket will be rolled over into the next auction and combined with the new accumulated fee basket. + +![img.png](./img.png) \ No newline at end of file diff --git a/.gitbook/developers-native/injective/auction/03_end_block.mdx b/.gitbook/developers-native/injective/auction/03_end_block.mdx deleted file mode 100644 index dc2ab98..0000000 --- a/.gitbook/developers-native/injective/auction/03_end_block.mdx +++ /dev/null @@ -1,21 +0,0 @@ ---- -sidebar_position: 3 -title: End-Block ---- - -# EndBlock - -### Auction Settlement - -The settlement of a given auction round occurs when `blockTime ≥ EndingTimeStamp.` If a non-zero INJ bid was placed during this period (i.e. there exists a `LastBid`), the following procedure will take place: - -* The winning INJ bid amount is burned. -* The basket of coins held by the auction module is transferred to the winning bidder. -* `LastAuctionResult` is written to state and `EventAuctionResult` is emitted. -* The `LastBid` is cleared. -* The AuctionRound is incremented by 1 and the EndingTimestamp is incremented by `AuctionPeriod`. -* The accumulated exchange fees are transferred from the `exchange` module to the `auction` module for the new upcoming auction. - -If the round closed without any successful bids, the existing coin basket will be rolled over into the next auction and combined with the new accumulated fee basket. - -![img.png](../../../developers/modules/injective/auction/img.png) diff --git a/.gitbook/developers-native/injective/auction/04_events.mdx b/.gitbook/developers-native/injective/auction/04_events.md similarity index 100% rename from .gitbook/developers-native/injective/auction/04_events.mdx rename to .gitbook/developers-native/injective/auction/04_events.md diff --git a/.gitbook/developers-native/injective/auction/05_params.mdx b/.gitbook/developers-native/injective/auction/05_params.md similarity index 100% rename from .gitbook/developers-native/injective/auction/05_params.mdx rename to .gitbook/developers-native/injective/auction/05_params.md diff --git a/.gitbook/developers-native/injective/auction/99_errors.mdx b/.gitbook/developers-native/injective/auction/99_errors.md similarity index 100% rename from .gitbook/developers-native/injective/auction/99_errors.mdx rename to .gitbook/developers-native/injective/auction/99_errors.md diff --git a/.gitbook/developers-native/injective/auction.mdx b/.gitbook/developers-native/injective/auction/index.md similarity index 100% rename from .gitbook/developers-native/injective/auction.mdx rename to .gitbook/developers-native/injective/auction/index.md diff --git a/.gitbook/developers-native/injective/erc20.mdx b/.gitbook/developers-native/injective/erc20.mdx deleted file mode 100644 index 1e39d52..0000000 --- a/.gitbook/developers-native/injective/erc20.mdx +++ /dev/null @@ -1,13 +0,0 @@ -# ERC20 - -## Abstract - -The erc20 module allows for the associations of existing bank denoms with ERC-20 tokens. - - -## Contents - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** diff --git a/.gitbook/developers-native/injective/erc20/01_concepts.mdx b/.gitbook/developers-native/injective/erc20/01_concepts.md similarity index 100% rename from .gitbook/developers-native/injective/erc20/01_concepts.mdx rename to .gitbook/developers-native/injective/erc20/01_concepts.md diff --git a/.gitbook/developers-native/injective/erc20/02_state.mdx b/.gitbook/developers-native/injective/erc20/02_state.md similarity index 100% rename from .gitbook/developers-native/injective/erc20/02_state.mdx rename to .gitbook/developers-native/injective/erc20/02_state.md diff --git a/.gitbook/developers-native/injective/erc20/03_messages.mdx b/.gitbook/developers-native/injective/erc20/03_messages.md similarity index 100% rename from .gitbook/developers-native/injective/erc20/03_messages.mdx rename to .gitbook/developers-native/injective/erc20/03_messages.md diff --git a/.gitbook/developers-native/injective/erc20/04_events.mdx b/.gitbook/developers-native/injective/erc20/04_events.md similarity index 100% rename from .gitbook/developers-native/injective/erc20/04_events.mdx rename to .gitbook/developers-native/injective/erc20/04_events.md diff --git a/.gitbook/developers-native/injective/erc20/index.md b/.gitbook/developers-native/injective/erc20/index.md new file mode 100644 index 0000000..7901f8a --- /dev/null +++ b/.gitbook/developers-native/injective/erc20/index.md @@ -0,0 +1,13 @@ +# ERC20 + +## Abstract + +The erc20 module allows for the associations of existing bank denoms with ERC-20 tokens. + + +## Contents + +1. **[Concepts](./01_concepts.md)** +2. **[State](./02_state.md)** +3. **[Messages](./03_messages.md)** +4. **[Events](./04_events.md)** diff --git a/.gitbook/developers-native/injective/evm.mdx b/.gitbook/developers-native/injective/evm.mdx deleted file mode 100644 index 4efc1d6..0000000 --- a/.gitbook/developers-native/injective/evm.mdx +++ /dev/null @@ -1,2 +0,0 @@ -# EVM - diff --git a/.gitbook/developers-native/injective/evm/01_concepts.mdx b/.gitbook/developers-native/injective/evm/01_concepts.md similarity index 100% rename from .gitbook/developers-native/injective/evm/01_concepts.mdx rename to .gitbook/developers-native/injective/evm/01_concepts.md diff --git a/.gitbook/developers-native/injective/evm/02_state.mdx b/.gitbook/developers-native/injective/evm/02_state.md similarity index 100% rename from .gitbook/developers-native/injective/evm/02_state.mdx rename to .gitbook/developers-native/injective/evm/02_state.md diff --git a/.gitbook/developers-native/injective/evm/03_state_transitions.mdx b/.gitbook/developers-native/injective/evm/03_state_transitions.md similarity index 100% rename from .gitbook/developers-native/injective/evm/03_state_transitions.mdx rename to .gitbook/developers-native/injective/evm/03_state_transitions.md diff --git a/.gitbook/developers-native/injective/evm/04_transactions.mdx b/.gitbook/developers-native/injective/evm/04_transactions.md similarity index 100% rename from .gitbook/developers-native/injective/evm/04_transactions.mdx rename to .gitbook/developers-native/injective/evm/04_transactions.md diff --git a/.gitbook/developers-native/injective/evm/05_abci.mdx b/.gitbook/developers-native/injective/evm/05_abci.md similarity index 100% rename from .gitbook/developers-native/injective/evm/05_abci.mdx rename to .gitbook/developers-native/injective/evm/05_abci.md diff --git a/.gitbook/developers-native/injective/evm/06_hooks.mdx b/.gitbook/developers-native/injective/evm/06_hooks.md similarity index 100% rename from .gitbook/developers-native/injective/evm/06_hooks.mdx rename to .gitbook/developers-native/injective/evm/06_hooks.md diff --git a/.gitbook/developers-native/injective/evm/07_events.mdx b/.gitbook/developers-native/injective/evm/07_events.md similarity index 100% rename from .gitbook/developers-native/injective/evm/07_events.mdx rename to .gitbook/developers-native/injective/evm/07_events.md diff --git a/.gitbook/developers-native/injective/evm/08_params.mdx b/.gitbook/developers-native/injective/evm/08_params.md similarity index 100% rename from .gitbook/developers-native/injective/evm/08_params.mdx rename to .gitbook/developers-native/injective/evm/08_params.md diff --git a/.gitbook/developers-native/injective/evm/09_client.mdx b/.gitbook/developers-native/injective/evm/09_client.md similarity index 100% rename from .gitbook/developers-native/injective/evm/09_client.mdx rename to .gitbook/developers-native/injective/evm/09_client.md diff --git a/.gitbook/developers-native/injective/exchange.mdx b/.gitbook/developers-native/injective/exchange.mdx deleted file mode 100644 index 690cfb7..0000000 --- a/.gitbook/developers-native/injective/exchange.mdx +++ /dev/null @@ -1,29 +0,0 @@ -# Exchange - -## Abstract - -The `exchange` module is the heart of the Injective Chain which enables fully decentralized spot and derivative exchange.\ -It is the _sine qua non_ module of the chain and integrates tightly with the `auction`, `insurance`, `oracle`, and `peggy` modules. - -The exchange protocol enables traders to create and trade on arbitrary spot and derivative markets.\ -The entire process of orderbook management, trade execution, order matching and settlement occurs on chain through the logic codified by the exchange module. - -The `exchange` module enables the exchange of tokens on two types of markets: - -1. `Derivative Market`: Either a `Perpetual Swap Market` or a `Futures Market`. -2. `Spot Market` - -## Contents - -1. [Derivative Market Concepts](00_derivative_market_concepts.md) -2. [Spot Market Concepts](01_spot_market_concepts.md) -3. [Other Concepts](02_other_concepts.md) -4. [State](03_state.md) -5. [State Transitions](04_state_transitions.md) -6. [Messages](05_messages.md) -7. [Proposals](06_proposals.md) -8. [Begin Block](07_begin_block.md) -9. [End Block](08_end_block.md) -10. [Events](09_events.md) -11. [Params](10_params.md) -12. [MsgPrivilegedExecuteContract](11_msg_privileged_execute_contract.md) diff --git a/.gitbook/developers-native/injective/exchange/00_derivative_market_concepts.mdx b/.gitbook/developers-native/injective/exchange/00_derivative_market_concepts.md similarity index 56% rename from .gitbook/developers-native/injective/exchange/00_derivative_market_concepts.mdx rename to .gitbook/developers-native/injective/exchange/00_derivative_market_concepts.md index 341ec7b..f122795 100644 --- a/.gitbook/developers-native/injective/exchange/00_derivative_market_concepts.mdx +++ b/.gitbook/developers-native/injective/exchange/00_derivative_market_concepts.md @@ -3,18 +3,18 @@ sidebar_position: 1 title: Derivative Market Concept --- -# Derivative Markets Concepts +# Derivative Market Concepts ## Definitions -In a derivative market using linear contracts (as opposed to inverse contracts), a contract with ticker **AAA/BBB**\ -offers exposure to the underlying AAA using the quote currency BBB for margin and settlement. For each contract, the\ +In a derivative market using linear contracts (as opposed to inverse contracts), a contract with ticker **AAA/BBB** +offers exposure to the underlying AAA using the quote currency BBB for margin and settlement. For each contract, the quotation unit is the BBB price of one unit of AAA, e.g. the USDT price of one unit of ETH. **Notional** - the notional value of a position is: `notional = quantity * price`. -**Refunds -** In our clearing system, a refund refers to the action of incrementing the **available balance** of an\ -account. This liberation of funds occurs as the result of an encumbrance being lifted from the account (e.g. cancelling\ +**Refunds -** In our clearing system, a refund refers to the action of incrementing the **available balance** of an +account. This liberation of funds occurs as the result of an encumbrance being lifted from the account (e.g. cancelling a limit order, reducing an order's payable fee to a maker fee, using less margin to fund a market order, etc.). ## Perpetual Market Trading Lifecycle @@ -27,31 +27,31 @@ A market is first created either by the instant launch functionality through `Ms #### Depositing Funds into Exchange -A trader can deposit funds, e.g., USDT, into the exchange by sending a `MsgDeposit` which transfers coins from the\ +A trader can deposit funds, e.g., USDT, into the exchange by sending a `MsgDeposit` which transfers coins from the Cosmos-SDK bank module to the trader's subaccount deposits on the exchange module. -Depositing a given `Amount` of coin will increment both the trader's subaccount deposit `AvailableBalance`\ +Depositing a given `Amount` of coin will increment both the trader's subaccount deposit `AvailableBalance` and `TotalBalance` by `Amount`. #### Withdrawing Funds from Exchange -A trader can withdraw funds from the exchange by sending a `MsgWithdraw` which transfers coins from the trader's subaccount\ +A trader can withdraw funds from the exchange by sending a `MsgWithdraw` which transfers coins from the trader's subaccount on the exchange module. -**Withdrawal Requirement:** Withdrawing a given `Amount` of coin will decrement both the trader's subaccount\ -deposit `AvailableBalance` and `TotalBalance` by `Amount`. Note: `Amount` must be less than or equal\ +**Withdrawal Requirement:** Withdrawing a given `Amount` of coin will decrement both the trader's subaccount +deposit `AvailableBalance` and `TotalBalance` by `Amount`. Note: `Amount` must be less than or equal to `AvailableBalance`. #### Transferring Funds between Subaccounts -A trader can transfer funds between his own subaccounts sending a `MsgSubaccountTransfer` which transfer coins from one of\ +A trader can transfer funds between his own subaccounts sending a `MsgSubaccountTransfer` which transfer coins from one of the trader's subaccount deposits to another subaccount also owned by the trader. Subaccount transfers have the same Withdrawal Requirement as normal withdrawals. #### Transferring Funds to another Exchange Account -A trader can transfer funds to an external account by sending a `MsgExternalTransfer` which transfers funds from the\ +A trader can transfer funds to an external account by sending a `MsgExternalTransfer` which transfers funds from the trader's subaccount to another third-party account. External Funds transfers have the same Withdrawal Requirement as normal withdrawals. @@ -60,25 +60,25 @@ External Funds transfers have the same Withdrawal Requirement as normal withdraw #### Placing Limit Orders -A trader can post a limit buy or sell order by sending a `MsgCreateDerivativeLimitOrder`. Upon submission, the order can\ +A trader can post a limit buy or sell order by sending a `MsgCreateDerivativeLimitOrder`. Upon submission, the order can be: -1. Immediately (fully or partially) matched against other opposing resting orders on the orderbook in the Endblocker\ +1. Immediately (fully or partially) matched against other opposing resting orders on the orderbook in the Endblocker batch auction, thus establishing a position for the user. 2. Added to the orderbook. -Note that it is possible for an order to be partially matched and for the remaining unmatched portion to be added to the\ +Note that it is possible for an order to be partially matched and for the remaining unmatched portion to be added to the orderbook. #### Placing Market Orders -A trader can post a market buy or sell order by sending a `MsgCreateDerivativeMarketOrder`. Upon submission, the market\ -order will be executed against other opposing resting orders on the orderbook in the Endblocker batch auction, thus\ +A trader can post a market buy or sell order by sending a `MsgCreateDerivativeMarketOrder`. Upon submission, the market +order will be executed against other opposing resting orders on the orderbook in the Endblocker batch auction, thus establishing a position for the user. #### Cancelling Limit Orders -User cancels a limit buy or sell order by sending a `MsgCancelDerivativeOrder` which removes the user's limit order from\ +User cancels a limit buy or sell order by sending a `MsgCancelDerivativeOrder` which removes the user's limit order from the orderbook. ### Increasing Position Margin @@ -87,32 +87,34 @@ A user can increase the margin of a position by sending a `MsgIncreasePositionMa ### Liquidating Insolvent Positions -A third party can liquidate any user's position if the position's maintenance margin ratio is breached by sending a`MsgLiquidatePosition`. +A third party can liquidate any user's position if the position's maintenance margin ratio is breached by sending a +`MsgLiquidatePosition`. **Initial Margin Requirement** -This is the requirement for the ratio of margin to the order's notional as well as the mark price when creating a new position.\ -The idea behind the additional mark price requirement is to minimize the liquidation risk when traded prices and mark prices\ +This is the requirement for the ratio of margin to the order's notional as well as the mark price when creating a new position. +The idea behind the additional mark price requirement is to minimize the liquidation risk when traded prices and mark prices temporally diverge too far from each other. Given the initial margin ratio, an order must fulfill two requirements: -* The margin must fulfill: `Margin ≥ InitialMarginRatio * Price * Quantity`, e.g., in a market with maximally 20x leverage,\ +- The margin must fulfill: `Margin ≥ InitialMarginRatio * Price * Quantity`, e.g., in a market with maximally 20x leverage, the initial margin ratio would be 0.05. Any new position will have a margin which is at least 0.05 of its notional. -* The margin must fulfill the mark price requirement: -* `Margin ≥ Quantity * (InitialMarginRatio * MarkPrice - PNL)` +- The margin must fulfill the mark price requirement: + +- `Margin >= Quantity * (InitialMarginRatio * MarkPrice - PNL)` PNL is the expected profit and loss of the position if it was closed at the current MarkPrice. Solved for MarkPrice this results in: -* For Buys: $\mathrm{MarkPrice}$ ≥ $\mathrm{\frac{Margin - Price \* Quantity}{(InitialMarginRatio - 1) \* Quantity\}}$ -* For Sells: $\mathrm{MarkPrice}$ ≤ $\mathrm{\frac{Margin + Price \* Quantity}{(InitialMarginRatio + 1) \* Quantity\}}$ +- For Buys: $\mathrm{MarkPrice}$ ≥ $\mathrm{\frac{Margin - Price * Quantity}{(InitialMarginRatio - 1) * Quantity}}$ +- For Sells: $\mathrm{MarkPrice}$ ≤ $\mathrm{\frac{Margin + Price * Quantity}{(InitialMarginRatio + 1) * Quantity}}$ **Maintenance Margin Requirement** -Throughout the lifecycle of an active position, if the following margin requirement is not met, the position is subject\ -to liquidation. (Note: for simplicity of notation but without loss of generality, we assume the position considered does\ +Throughout the lifecycle of an active position, if the following margin requirement is not met, the position is subject +to liquidation. (Note: for simplicity of notation but without loss of generality, we assume the position considered does not have any funding). -* For Longs: `Margin ≥ Quantity * MaintenanceMarginRatio * MarkPrice - (MarkPrice - EntryPrice)` -* For Shorts: `Margin ≥ Quantity * MaintenanceMarginRatio * MarkPrice - (EntryPrice - MarkPrice)` +- For Longs: `Margin >= Quantity * MaintenanceMarginRatio * MarkPrice - (MarkPrice - EntryPrice)` +- For Shorts: `Margin >= Quantity * MaintenanceMarginRatio * MarkPrice - (EntryPrice - MarkPrice)` **Liquidation Payouts** @@ -124,117 +126,119 @@ Also note that liquidations are executed immediately in a block before any other ### Funding Payments -Funding exists only for perpetual markets as a mechanism to align trading prices with the mark price. It refers to the\ -periodic payments exchanged between the traders that are long or short of a contract at the end of every funding epoch,\ +Funding exists only for perpetual markets as a mechanism to align trading prices with the mark price. It refers to the +periodic payments exchanged between the traders that are long or short of a contract at the end of every funding epoch, e.g. every hour. When the funding rate is positive, longs pay shorts. When it is negative, shorts pay longs. -* `Position Size = Position Quantity * MarkPrice` -* `Funding Payment = Position Size * Hourly Funding Rate (HFR)` -* `HFR = Cap((TWAP((SyntheticVWAPExecutionPrice - MarkPrice)/MarkPrice) + DailyInterestRate) * 1/24)` -* `SyntheticVWAPExecutionPrice = (Price_A*Volume_A +Price_B*Volume_B +Price_C*Volume_C)/(Volume_A + Volume_B + Volume_C)` - * `A` is the market buy batch execution - * `B` is the market sell batch execution - * `C` is the limit matching batch execution +- `Position Size = Position Quantity * MarkPrice` +- `Funding Payment = Position Size * Hourly Funding Rate (HFR)` +- `HFR = Cap((TWAP((SyntheticVWAPExecutionPrice - MarkPrice)/MarkPrice) + DailyInterestRate) * 1/24)` +- `SyntheticVWAPExecutionPrice = (Price_A*Volume_A +Price_B*Volume_B +Price_C*Volume_C)/(Volume_A + Volume_B + Volume_C)` + - `A` is the market buy batch execution + - `B` is the market sell batch execution + - `C` is the limit matching batch execution Funding payments are applied to the whole market by modifying the `CumulativeFunding` value. Each position stores the current `CumulativeFunding` as `CumulativeFundingEntry`. Subsequent funding payments are only applied upon position changes and can be calculated as: -* FundingPayment - * For Longs: `FundingPayment ← PositionQuantity * (CumulativeFunding - CumulativeFundingEntry)` - * For Shorts: `FundingPayment ← PositionQuantity * (CumulativeFundingEntry - CumulativeFunding)` -* `Margin' ← Margin + FundingPayment` -* `CumulativeFundingEntry' ← CumulativeFunding` +- FundingPayment + - For Longs: `FundingPayment ← PositionQuantity * (CumulativeFunding - CumulativeFundingEntry)` + - For Shorts: `FundingPayment ← PositionQuantity * (CumulativeFundingEntry - CumulativeFunding)` +- `Margin' ← Margin + FundingPayment` +- `CumulativeFundingEntry' ← CumulativeFunding` ## Perpetual Market Trading Specification ### Positions -A trader's position records the conditions under which the trader has entered into the derivative contract and is\ +A trader's position records the conditions under which the trader has entered into the derivative contract and is defined as follows -* Position Definition: - * `Quantity` - * `EntryPrice` - * `Margin` - * `HoldQuantity` - * `CumulativeFundingEntry` +- Position Definition: + - `Quantity` + - `EntryPrice` + - `Margin` + - `HoldQuantity` + - `CumulativeFundingEntry` As an example, consider the following position in the ETH/USDT market: -* `Quantity` = -2 -* `EntryPrice` = 2200 -* `Margin` = 800 -* `HoldQuantity` = 1 -* `CumulativeFundingEntry` = 4838123 +- `Quantity` = -2 +- `EntryPrice` = 2200 +- `Margin` = 800 +- `HoldQuantity` = 1 +- `CumulativeFundingEntry` = 4838123 -This position represents short exposure for 2 contracts of the ETH/USDT market collateralized with 800 USDT, with an\ -entry price of 2200. The `HoldQuantity` represents the quantity of the position that the trader has opposing orders for.`CumulativeFundingEntry` represents the cumulative funding value that the position was last updated at. +This position represents short exposure for 2 contracts of the ETH/USDT market collateralized with 800 USDT, with an +entry price of 2200. The `HoldQuantity` represents the quantity of the position that the trader has opposing orders for. +`CumulativeFundingEntry` represents the cumulative funding value that the position was last updated at. Position Netting: -When a new vanilla order is matched for a subaccount with an existing position, the new position will be the result from\ -netting the existing position with the new vanilla order. A matched vanilla order produces a position delta defined by`FillQuantity`, `FillMargin` and `ClearingPrice`. +When a new vanilla order is matched for a subaccount with an existing position, the new position will be the result from +netting the existing position with the new vanilla order. A matched vanilla order produces a position delta defined by +`FillQuantity`, `FillMargin` and `ClearingPrice`. -* Applying Position Delta to a position in the same direction: - * `Entry Price' ← (Quantity \* EntryPrice + FillQuantity \* ClearingPrice) / (Quantity + FillQuantity)` - * `Quantity' ← Quantity + FillQuantity` - * `Margin' ← Margin + FillMargin` -* Apply Position Delta to a position in the opposing direction: - * `Entry Price - no change` - * `Quantity' ← Quantity - FillQuantity` - * `Margin' ← Margin \* (Quantity - FillQuantity) / Quantity` +- Applying Position Delta to a position in the same direction: + - `Entry Price' ← (Quantity \* EntryPrice + FillQuantity \* ClearingPrice) / (Quantity + FillQuantity)` + - `Quantity' ← Quantity + FillQuantity` + - `Margin' ← Margin + FillMargin` +- Apply Position Delta to a position in the opposing direction: + - `Entry Price - no change` + - `Quantity' ← Quantity - FillQuantity` + - `Margin' ← Margin \* (Quantity - FillQuantity) / Quantity` ### Limit Buy Order -A limit buy order seeks to purchase a specified Quantity of a derivative contract at a specified Price by providing a\ +A limit buy order seeks to purchase a specified Quantity of a derivative contract at a specified Price by providing a specified amount of margin as collateral. ### Limit Sell Order -A limit sell order seeks to sell a specified Quantity of a derivative contract at a specified Price by providing a\ +A limit sell order seeks to sell a specified Quantity of a derivative contract at a specified Price by providing a specified amount of margin as collateral. -A matched position will have **subtracted fees** which depend on whether the limit order becomes executed as a\ +A matched position will have **subtracted fees** which depend on whether the limit order becomes executed as a maker order or a taker order. ### Market Buy Order -A market buy order seeks to purchase a specified Quantity of a derivative contract at a specified worst price using\ +A market buy order seeks to purchase a specified Quantity of a derivative contract at a specified worst price using the subaccount's available balance as margin collateral. -Handler and EndBlocker Execution of the market order are conceptually identical to the Limit Buy Order\ -(Immediately Matched case), since the trader passes the margin which implicitly sets a maximum price limit due to the\ +Handler and EndBlocker Execution of the market order are conceptually identical to the Limit Buy Order +(Immediately Matched case), since the trader passes the margin which implicitly sets a maximum price limit due to the initial min margin requirements. ### Market Sell Order -A market sell order seeks to sell a specified Quantity of a derivative contract at a specified worst price using the\ +A market sell order seeks to sell a specified Quantity of a derivative contract at a specified worst price using the subaccount's available balance as margin collateral. -Handler and EndBlocker Execution of the market order are conceptually identical to the Limit Sell Order\ -(Immediately Matched case), since the trader passes the margin which implicitly sets a minimum price limit due to the\ +Handler and EndBlocker Execution of the market order are conceptually identical to the Limit Sell Order +(Immediately Matched case), since the trader passes the margin which implicitly sets a minimum price limit due to the initial min margin requirements. ### Order Types -* BUY (1): A standard buy order to purchase an asset at either the current market price or a set limit price. -* SELL (2): A standard sell order to sell an asset at either the current market price or a set limit price. -* STOP\_BUY (3): A stop-buy order converts into a regular buy order once the oracle price reaches or surpasses a specified trigger price. -* STOP\_SELL (4): A stop-sell order becomes a regular sell order once the oracle price drops to or below a specified trigger price. -* TAKE\_BUY (5): A take-buy order converts into a regular buy order once the oracle price reaches or drops below a specified trigger price. -* TAKE\_SELL (6):A stop-sell order becomes a regular sell order once the oracle price reaches or surpasses a specified trigger price. -* BUY\_PO (7): Post-Only Buy. This order type ensures that the order will only be added to the order book and not match with a pre-existing order. It guarantees that you will be the market "maker" and not the "taker". -* SELL\_PO (8): Post-Only Sell. Similar to BUY\_PO, this ensures that your sell order will only add liquidity to the order book and not match with a pre-existing order. -* BUY\_ATOMIC (9): An atomic buy order is a market order that gets executed instantly, bypassing the Frequent Batch Auctions (FBA). It's intended for smart contracts that need to execute a trade instantly. A higher fee is paid defined in the global exchange parameters. -* SELL\_ATOMIC (10): An atomic sell order is similar to a BUY\_ATOMIC, and it gets executed instantly at the current market price, bypassing the FBA. +- BUY (1): A standard buy order to purchase an asset at either the current market price or a set limit price. +- SELL (2): A standard sell order to sell an asset at either the current market price or a set limit price. +- STOP_BUY (3): A stop-buy order converts into a regular buy order once the oracle price reaches or surpasses a specified trigger price. +- STOP_SELL (4): A stop-sell order becomes a regular sell order once the oracle price drops to or below a specified trigger price. +- TAKE_BUY (5): A take-buy order converts into a regular buy order once the oracle price reaches or drops below a specified trigger price. +- TAKE_SELL (6):A stop-sell order becomes a regular sell order once the oracle price reaches or surpasses a specified trigger price. +- BUY_PO (7): Post-Only Buy. This order type ensures that the order will only be added to the order book and not match with a pre-existing order. It guarantees that you will be the market "maker" and not the "taker". +- SELL_PO (8): Post-Only Sell. Similar to BUY_PO, this ensures that your sell order will only add liquidity to the order book and not match with a pre-existing order. +- BUY_ATOMIC (9): An atomic buy order is a market order that gets executed instantly, bypassing the Frequent Batch Auctions (FBA). It's intended for smart contracts that need to execute a trade instantly. A higher fee is paid defined in the global exchange parameters. +- SELL_ATOMIC (10): An atomic sell order is similar to a BUY_ATOMIC, and it gets executed instantly at the current market price, bypassing the FBA. ### Reduce-Only Orders (Selling Positions) ### Limit Buy Reduce-Only Order -A limit buy reduce-only order seeks to reduce existing long exposure by a specified `Quantity` ETH (**base currency**).\ +A limit buy reduce-only order seeks to reduce existing long exposure by a specified `Quantity` ETH (**base currency**). The payout for closing a position will have **subtracted fees**. ### Limit Sell Reduce-Only Order -A limit sell reduce-only order seeks to reduce existing short exposure by a specified `Quantity` ETH (**base currency**).\ +A limit sell reduce-only order seeks to reduce existing short exposure by a specified `Quantity` ETH (**base currency**). The payout for closing a position will have **subtracted fees**. diff --git a/.gitbook/developers-native/injective/exchange/01_spot_market_concepts.mdx b/.gitbook/developers-native/injective/exchange/01_spot_market_concepts.md similarity index 55% rename from .gitbook/developers-native/injective/exchange/01_spot_market_concepts.mdx rename to .gitbook/developers-native/injective/exchange/01_spot_market_concepts.md index 8b07574..6d413d3 100644 --- a/.gitbook/developers-native/injective/exchange/01_spot_market_concepts.mdx +++ b/.gitbook/developers-native/injective/exchange/01_spot_market_concepts.md @@ -3,7 +3,7 @@ sidebar_position: 2 title: Spot Market Concepts --- -# Spot Markets Concepts +# Spot Market Concepts ## Definitions @@ -11,71 +11,71 @@ In a Spot Market with ticker **AAA/BBB, AAA is the base asset, BBB is the quote For example, in the ETH/USDT market -* ETH is base asset -* USDT is the quote asset +- ETH is base asset +- USDT is the quote asset -The spot market's **price** refers to how much USDT (the quote asset) is required for one unit of ETH (the base\ +The spot market's **price** refers to how much USDT (the quote asset) is required for one unit of ETH (the base asset). For all spot markets, **fees are always paid in the quote asset**, e.g., USDT. **Debit vs Credit** -* **Debit Amount** refers to the amount of asset that is withdrawn from an account. -* **Credit Amount** refers to the amount of asset that is deposited to an account. +- **Debit Amount** refers to the amount of asset that is withdrawn from an account. +- **Credit Amount** refers to the amount of asset that is deposited to an account. **Refunds** -In our system, a refund refers to the action of incrementing the **available balance** of an account. This liberation of\ -funds occurs as the result of an encumbrance being lifted from the account (e.g. cancelling a limit order, reducing an\ +In our system, a refund refers to the action of incrementing the **available balance** of an account. This liberation of +funds occurs as the result of an encumbrance being lifted from the account (e.g. cancelling a limit order, reducing an order's payable fee to a maker fee, using less margin to fund a market order, etc.). ### Limit Buy Order -A limit buy order seeks to buy a specified `Quantity` ETH (**base asset**) in exchange for `Quantity * Price` amount of\ -USDT (**quote asset**) **plus fees** which depend on whether the limit order becomes executed as a maker order or a\ +A limit buy order seeks to buy a specified `Quantity` ETH (**base asset**) in exchange for `Quantity * Price` amount of +USDT (**quote asset**) **plus fees** which depend on whether the limit order becomes executed as a maker order or a taker order. ### Limit Sell Order -A limit sell order seeks to sell a specified `Quantity` ETH (**base asset**) in exchange for `Quantity * Price` amount\ -of USDT (**quote asset**) **minus fees** which depend on whether the limit order becomes executed as a maker order or a\ +A limit sell order seeks to sell a specified `Quantity` ETH (**base asset**) in exchange for `Quantity * Price` amount +of USDT (**quote asset**) **minus fees** which depend on whether the limit order becomes executed as a maker order or a taker order. ### Market Buy Order -A market buy order seeks to buy a specified `Quantity` ETH (**base asset**) at a specified worst price which is at or near\ +A market buy order seeks to buy a specified `Quantity` ETH (**base asset**) at a specified worst price which is at or near the current ask using the respective account quote asset balance (USDT) as collateral\*\* (inclusive of fees). -As a result, each market buy order implicitly has a maximum acceptable price associated with it, as filling the market\ +As a result, each market buy order implicitly has a maximum acceptable price associated with it, as filling the market order beyond that price would simply fail due to a lack of funds. ### Market Sell Order -A market sell order seeks to sell a specified `Quantity` ETH (**base asset**) at a specified worst price which is at or\ +A market sell order seeks to sell a specified `Quantity` ETH (**base asset**) at a specified worst price which is at or near the current bid in exchange for any amount of the quote asset (USDT) available in the market. As a result, each market sell order implicitly has a zero price associated with it. ### Order Types -* BUY (1): A standard buy order to purchase an asset at either the current market price or a set limit price. -* SELL (2): A standard sell order to sell an asset at either the current market price or a set limit price. -* STOP\_BUY (3): This order type is not supported for spot markets. -* STOP\_SELL (4): This order type is not supported for spot markets. -* TAKE\_BUY (5): This order type is not supported for spot markets. -* TAKE\_SELL (6): This order type is not supported for spot markets. -* BUY\_PO (7): Post-Only Buy. This order type ensures that the order will only be added to the order book and not match with a pre-existing order. It guarantees that you will be the market "maker" and not the "taker". -* SELL\_PO (8): Post-Only Sell. Similar to BUY\_PO, this ensures that your sell order will only add liquidity to the order book and not match with a pre-existing order. -* BUY\_ATOMIC (9): An atomic buy order is a market order that gets executed instantly, bypassing the Frequent Batch Auctions (FBA). It's intended for smart contracts that need to execute a trade instantly. A higher fee is paid defined in the global exchange parameters. -* SELL\_ATOMIC (10): An atomic sell order is similar to a BUY\_ATOMIC, and it gets executed instantly at the current market price, bypassing the FBA. +- BUY (1): A standard buy order to purchase an asset at either the current market price or a set limit price. +- SELL (2): A standard sell order to sell an asset at either the current market price or a set limit price. +- STOP_BUY (3): This order type is not supported for spot markets. +- STOP_SELL (4): This order type is not supported for spot markets. +- TAKE_BUY (5): This order type is not supported for spot markets. +- TAKE_SELL (6): This order type is not supported for spot markets. +- BUY_PO (7): Post-Only Buy. This order type ensures that the order will only be added to the order book and not match with a pre-existing order. It guarantees that you will be the market "maker" and not the "taker". +- SELL_PO (8): Post-Only Sell. Similar to BUY_PO, this ensures that your sell order will only add liquidity to the order book and not match with a pre-existing order. +- BUY_ATOMIC (9): An atomic buy order is a market order that gets executed instantly, bypassing the Frequent Batch Auctions (FBA). It's intended for smart contracts that need to execute a trade instantly. A higher fee is paid defined in the global exchange parameters. +- SELL_ATOMIC (10): An atomic sell order is similar to a BUY_ATOMIC, and it gets executed instantly at the current market price, bypassing the FBA. ### Market Data Requirements -Orderbook data aside, so long as our Chain supports the **base capability** to obtain Tick by Tick trading data,\ +Orderbook data aside, so long as our Chain supports the **base capability** to obtain Tick by Tick trading data, aggregations can be applied to obtain most of the necessary higher order data, including -* OHLCV data -* Account Trading History -* Market Statistics +- OHLCV data +- Account Trading History +- Market Statistics ## Spot Market Lifecycle @@ -85,7 +85,7 @@ A market is first created either by the instant launch functionality through `Ms ### Listing Fee based Spot Market Creation -Allow anyone to create an active spot market of their choice without requiring governance approval by burning a pre-set\ +Allow anyone to create an active spot market of their choice without requiring governance approval by burning a pre-set SpotMarketInstantListingFee of INJ. We should still check that the denom is valid though. @@ -105,12 +105,12 @@ If a spot market is an active state, it can accept orders and trades. #### Paused State -If a spot market is a paused state, it will no longer accept orders and trades and will also not allow any users to take\ +If a spot market is a paused state, it will no longer accept orders and trades and will also not allow any users to take actions on that market (no order cancellations). #### Suspended State -If a spot market is a suspended state, it will no longer accept orders and trades, and will only allow traders to cancel\ +If a spot market is a suspended state, it will no longer accept orders and trades, and will only allow traders to cancel their orders. ## Demolished State @@ -121,15 +121,15 @@ When a market becomes demolished, all outstanding orders are cancelled. There are three state transitions that correspond to the following status changes -* Activate Action - **Paused or Suspended Status → Active Status** -* Pause Action - **Active or Suspended Status → Paused Status** -* Suspend Action - **Active or Paused Status → Suspended Status** -* Demolish Action - **Paused or Suspended Status → Demolished Status** +- Activate Action - **Paused or Suspended Status → Active Status** +- Pause Action - **Active or Suspended Status → Paused Status** +- Suspend Action - **Active or Paused Status → Suspended Status** +- Demolish Action - **Paused or Suspended Status → Demolished Status** ### Spot Market Parameter Update The following parameters exist for Spot Markets -* SpotMarketInstantListingFee -* DefaultSpotMakerFeeRate -* DefaultSpotTakerFeeRate +- SpotMarketInstantListingFee +- DefaultSpotMakerFeeRate +- DefaultSpotTakerFeeRate diff --git a/.gitbook/developers-native/injective/exchange/02_binary_options_markets.mdx b/.gitbook/developers-native/injective/exchange/02_binary_options_markets.md similarity index 100% rename from .gitbook/developers-native/injective/exchange/02_binary_options_markets.mdx rename to .gitbook/developers-native/injective/exchange/02_binary_options_markets.md diff --git a/.gitbook/developers-native/injective/exchange/02_other_concepts.mdx b/.gitbook/developers-native/injective/exchange/02_other_concepts.md similarity index 82% rename from .gitbook/developers-native/injective/exchange/02_other_concepts.mdx rename to .gitbook/developers-native/injective/exchange/02_other_concepts.md index 8a1c327..d8a337a 100644 --- a/.gitbook/developers-native/injective/exchange/02_other_concepts.mdx +++ b/.gitbook/developers-native/injective/exchange/02_other_concepts.md @@ -7,27 +7,27 @@ title: Other Concepts ## Concurrency-Friendly Market Order Clearing Price Algorithm -We apply the [split-apply-combine](https://stackoverflow.com/tags/split-apply-combine/info) paradigm to leverage\ +We apply the [split-apply-combine](https://stackoverflow.com/tags/split-apply-combine/info) paradigm to leverage concurrency for efficient data processing. 1. Match all matchable orders (see order matching for details) concurrently in all markets. -* The intermediate result is a clearing price and a list of matched orders with their fill quantities. -* The final result is a temporary cache of all new events and all changes to positions, orders, subaccount deposits,\ +- The intermediate result is a clearing price and a list of matched orders with their fill quantities. +- The final result is a temporary cache of all new events and all changes to positions, orders, subaccount deposits, trading reward points and fees paid. 2. Wait for execution on all markets and persist all data. -Note: beyond just executing settlement, the design must also take into account market data dissemination requirements\ +Note: beyond just executing settlement, the design must also take into account market data dissemination requirements for off-chain consumption. ## Atomic Market Order Execution A common request from new applications built on Cosmwasm is for the ability to be notified upon the execution of an order. In the regular order execution flow, this would not be possible, since the Frequent Batch Auctions (FBA) are executed inside the EndBlocker. To circumvent the FBA, the new type of atomic market orders is introduced. For the privilege of executing such an atomic market order instantly, an additional trading fee is imposed. To calculate the fee of an atomic market order, the market's taker fee is multiplied by the market types's `AtomicMarketOrderFeeMultiplier`. -* `SpotAtomicMarketOrderFeeMultiplier` -* `DerivativeAtomicMarketOrderFeeMultiplier` -* `BinaryOptionsAtomicMarketOrderFeeMultiplier` +- `SpotAtomicMarketOrderFeeMultiplier` +- `DerivativeAtomicMarketOrderFeeMultiplier` +- `BinaryOptionsAtomicMarketOrderFeeMultiplier` These multipliers are defined the global exchange parameters. In addition, the exchange parameters also define the `AtomicMarketOrderAccessLevel` which specifies the minimum access level required to execute an atomic market order. @@ -44,13 +44,13 @@ const ( Governance approves a **TradingRewardCampaignLaunchProposal** which specifies: -* The first campaign's starting timestamp -* The **TradingRewardCampaignInfo** which specifies - * The campaign duration in seconds - * The accepted trading fee quote currency denoms - * The optional market-specific **boost** info - * The disqualified marketIDs for markets in which trades will not earn rewards -* The **CampaignRewardPools** which specifies the maximum epoch rewards that constitute the trading rewards pool for each successive campaign +- The first campaign's starting timestamp +- The **TradingRewardCampaignInfo** which specifies + - The campaign duration in seconds + - The accepted trading fee quote currency denoms + - The optional market-specific **boost** info + - The disqualified marketIDs for markets in which trades will not earn rewards +- The **CampaignRewardPools** which specifies the maximum epoch rewards that constitute the trading rewards pool for each successive campaign During a given campaign, the exchange will record each trader's cumulative trading reward points obtained from trading volume (with boosts applied, if applicable) from all eligible markets, i.e., markets with a matching quote currency that are not in the disqualified list. @@ -62,9 +62,9 @@ Campaigns will not auto-rollover. If there are no additional campaigns defined i Governance approves a **FeeDiscountProposal** which defines a fee discount **schedule** which specifies fee discount **tiers** which each specify the maker and taker discounts rates a trader will receive if they satisfy the specified minimum INJ staked amount AND have had at least the specified trading volume (based on the specified **quote denoms**) over the specified time period (`bucket count * bucket duration seconds`, which should equal 30 days). The schedule also specifies a list of disqualified marketIDs for markets whose trading volume will not count towards the volume contribution. -* Spot markets where the base and quote are both in the accepted quote currencies list will not be rewarded (e.g. the USDC/USDT spot market). -* Maker fills in markets with negative maker fees will NOT give the trader any fee discounts. -* If the fee discount proposal was passed less than 30 days ago, i.e. `BucketCount * BucketDuration` hasn't passed yet since the creation of the proposal, the fee volume requirement is ignored so we don't unfairly penalize market makers who onboard immediately. +- Spot markets where the base and quote are both in the accepted quote currencies list will not be rewarded (e.g. the USDC/USDT spot market). +- Maker fills in markets with negative maker fees will NOT give the trader any fee discounts. +- If the fee discount proposal was passed less than 30 days ago, i.e. `BucketCount * BucketDuration` hasn't passed yet since the creation of the proposal, the fee volume requirement is ignored so we don't unfairly penalize market makers who onboard immediately. Internally the trading volumes are stored in buckets, typically 30 buckets each lasting 24 hours. When a bucket is older than 30 days, it gets removed. Additionally for performance reasons there is a cache for retrieving the fee discount tier for an account. This cache is updated every 24 hours. diff --git a/.gitbook/developers-native/injective/exchange/03_state.mdx b/.gitbook/developers-native/injective/exchange/03_state.md similarity index 98% rename from .gitbook/developers-native/injective/exchange/03_state.mdx rename to .gitbook/developers-native/injective/exchange/03_state.md index a03f93b..94a80b9 100644 --- a/.gitbook/developers-native/injective/exchange/03_state.mdx +++ b/.gitbook/developers-native/injective/exchange/03_state.md @@ -61,7 +61,7 @@ type GenesisState struct { ## Params -`Params` is a module-wide configuration that stores system parameters and defines overall functioning of the exchange module.\ +`Params` is a module-wide configuration that stores system parameters and defines overall functioning of the exchange module. This configuration is modifiable by governance using params update proposal natively supported by `gov` module. It defines default fee objects to be used for spot and derivative markets and funding parameters for derivative markets and instant listing fees. @@ -184,7 +184,7 @@ type MarketOrderIndicator struct { ## SpotMarket -`SpotMarket` is the structure to store all the required information and state for a spot market.\ +`SpotMarket` is the structure to store all the required information and state for a spot market. Spot markets are stored by hash of the market to query the market efficiently. ```go @@ -215,7 +215,7 @@ type SpotMarket struct { ## SpotOrderBook -`SpotOrderBook` is a structure to store spot limit orders for a specific market.\ +`SpotOrderBook` is a structure to store spot limit orders for a specific market. Two objects are created, one for buy orders and one for sell orders. ```go @@ -261,7 +261,7 @@ type SpotMarketOrder struct { ## DerivativeMarket -`DerivativeMarket` is the structure to store all the required information and state for a derivative market.\ +`DerivativeMarket` is the structure to store all the required information and state for a derivative market. Derivative markets are stored by hash of the market to query the market efficiently. ```go @@ -304,7 +304,7 @@ type DerivativeMarket struct { ## DerivativeOrderBook -`DerivativeOrderBook` is a structure to store derivative limit orders for a specific market.\ +`DerivativeOrderBook` is a structure to store derivative limit orders for a specific market. Two objects are created, one for buy orders and one for sell orders. ```go @@ -398,7 +398,7 @@ type SubaccountPosition struct { ## ExpiryFuturesMarketInfo -`ExpiryFuturesMarketInfo` is a structure to keep the information of expiry futures market.\ +`ExpiryFuturesMarketInfo` is a structure to keep the information of expiry futures market. It is stored by the id of the market. ```go diff --git a/.gitbook/developers-native/injective/exchange/04_state_transitions.mdx b/.gitbook/developers-native/injective/exchange/04_state_transitions.md similarity index 100% rename from .gitbook/developers-native/injective/exchange/04_state_transitions.mdx rename to .gitbook/developers-native/injective/exchange/04_state_transitions.md diff --git a/.gitbook/developers-native/injective/exchange/05_messages.mdx b/.gitbook/developers-native/injective/exchange/05_messages.md similarity index 63% rename from .gitbook/developers-native/injective/exchange/05_messages.mdx rename to .gitbook/developers-native/injective/exchange/05_messages.md index 5819c73..5f465ae 100644 --- a/.gitbook/developers-native/injective/exchange/05_messages.mdx +++ b/.gitbook/developers-native/injective/exchange/05_messages.md @@ -5,8 +5,8 @@ title: Messages # Messages -In this section we describe the processing of the exchange messages and the corresponding updates to the state. All\ -created/modified state objects specified by each message are defined within the [State Transitions](04_state_transitions.md)\ +In this section we describe the processing of the exchange messages and the corresponding updates to the state. All +created/modified state objects specified by each message are defined within the [State Transitions](./04_state_transitions.md) section. ## Msg/Deposit @@ -25,9 +25,9 @@ type MsgDeposit struct { **Fields description** -* `Sender` field describes the address who deposits. -* `SubaccountId` describes the ID of a sub-account to receive a deposit. -* `Amount` specifies the deposit amount. +- `Sender` field describes the address who deposits. +- `SubaccountId` describes the ID of a sub-account to receive a deposit. +- `Amount` specifies the deposit amount. ## Msg/Withdraw @@ -44,9 +44,9 @@ type MsgWithdraw struct { **Fields description** -* `Sender` field describes the address to receive withdrawal. -* `SubaccountId` describes the ID of a sub-account to withdraw from. -* `Amount` specifies the withdrawal amount. +- `Sender` field describes the address to receive withdrawal. +- `SubaccountId` describes the ID of a sub-account to withdraw from. +- `Amount` specifies the withdrawal amount. ## Msg/InstantSpotMarketLaunch @@ -66,12 +66,12 @@ type MsgInstantSpotMarketLaunch struct { **Fields description** -* `Sender` field describes the creator of this msg. -* `Ticker` describes the ticker for the spot market. -* `BaseDenom` specifies the type of coin to use as the base currency. -* `QuoteDenom` specifies the type of coin to use as the quote currency. -* `MinPriceTickSize` defines the minimum tick size of the order's price. -* `MinQuantityTickSize` defines the minimum tick size of the order's quantity. +- `Sender` field describes the creator of this msg. +- `Ticker` describes the ticker for the spot market. +- `BaseDenom` specifies the type of coin to use as the base currency. +- `QuoteDenom` specifies the type of coin to use as the quote currency. +- `MinPriceTickSize` defines the minimum tick size of the order's price. +- `MinQuantityTickSize` defines the minimum tick size of the order's quantity. ## Msg/InstantPerpetualMarketLaunch @@ -98,19 +98,19 @@ type MsgInstantPerpetualMarketLaunch struct { **Fields description** -* `Sender` field describes the creator of this msg. -* `Ticker` field describes the ticker for the derivative market. -* `QuoteDenom` field describes the type of coin to use as the base currency. -* `OracleBase` field describes the oracle base currency. -* `OracleQuote` field describes the oracle quote currency. -* `OracleScaleFactor` field describes the scale factor for oracle prices. -* `OracleType` field describes the oracle type. -* `MakerFeeRate` field describes the trade fee rate for makers on the derivative market. -* `TakerFeeRate` field describes the trade fee rate for takers on the derivative market. -* `InitialMarginRatio` field describes the initial margin ratio for the derivative market. -* `MaintenanceMarginRatio` field describes the maintenance margin ratio for the derivative market. -* `MinPriceTickSize` field describes the minimum tick size of the order's price and margin. -* `MinQuantityTickSize` field describes the minimum tick size of the order's quantity. +- `Sender` field describes the creator of this msg. +- `Ticker` field describes the ticker for the derivative market. +- `QuoteDenom` field describes the type of coin to use as the base currency. +- `OracleBase` field describes the oracle base currency. +- `OracleQuote` field describes the oracle quote currency. +- `OracleScaleFactor` field describes the scale factor for oracle prices. +- `OracleType` field describes the oracle type. +- `MakerFeeRate` field describes the trade fee rate for makers on the derivative market. +- `TakerFeeRate` field describes the trade fee rate for takers on the derivative market. +- `InitialMarginRatio` field describes the initial margin ratio for the derivative market. +- `MaintenanceMarginRatio` field describes the maintenance margin ratio for the derivative market. +- `MinPriceTickSize` field describes the minimum tick size of the order's price and margin. +- `MinQuantityTickSize` field describes the minimum tick size of the order's quantity. ## Msg/InstantExpiryFuturesMarketLaunch @@ -138,20 +138,20 @@ type MsgInstantExpiryFuturesMarketLaunch struct { **Fields description** -* `Sender` field describes the creator of this msg. -* `Ticker` field describes the ticker for the derivative market. -* `QuoteDenom` field describes the type of coin to use as the quote currency. -* `OracleBase` field describes the oracle base currency. -* `OracleQuote` field describes the oracle quote currency. -* `OracleScaleFactor` field describes the scale factor for oracle prices. -* `OracleType` field describes the oracle type. -* `Expiry` field describes the expiration time of the market. -* `MakerFeeRate` field describes the trade fee rate for makers on the derivative market. -* `TakerFeeRate` field describes the trade fee rate for takers on the derivative market. -* `InitialMarginRatio` field describes the initial margin ratio for the derivative market. -* `MaintenanceMarginRatio` field describes the maintenance margin ratio for the derivative market. -* `MinPriceTickSize` field describes the minimum tick size of the order's price and margin. -* `MinQuantityTickSize` field describes the minimum tick size of the order's quantity. +- `Sender` field describes the creator of this msg. +- `Ticker` field describes the ticker for the derivative market. +- `QuoteDenom` field describes the type of coin to use as the quote currency. +- `OracleBase` field describes the oracle base currency. +- `OracleQuote` field describes the oracle quote currency. +- `OracleScaleFactor` field describes the scale factor for oracle prices. +- `OracleType` field describes the oracle type. +- `Expiry` field describes the expiration time of the market. +- `MakerFeeRate` field describes the trade fee rate for makers on the derivative market. +- `TakerFeeRate` field describes the trade fee rate for takers on the derivative market. +- `InitialMarginRatio` field describes the initial margin ratio for the derivative market. +- `MaintenanceMarginRatio` field describes the maintenance margin ratio for the derivative market. +- `MinPriceTickSize` field describes the minimum tick size of the order's price and margin. +- `MinQuantityTickSize` field describes the minimum tick size of the order's quantity. ## Msg/CreateSpotLimitOrder @@ -166,8 +166,8 @@ type MsgCreateSpotLimitOrder struct { **Fields description** -* `Sender` field describes the creator of this msg. -* `Order` field describes the order info. +- `Sender` field describes the creator of this msg. +- `Order` field describes the order info. ## Msg/BatchCreateSpotLimitOrders @@ -182,8 +182,8 @@ type MsgBatchCreateSpotLimitOrders struct { **Fields description** -* `Sender` field describes the creator of this msg. -* `Orders` field describes the orders info. +- `Sender` field describes the creator of this msg. +- `Orders` field describes the orders info. ## Msg/CreateSpotMarketOrder @@ -198,8 +198,8 @@ type MsgCreateSpotMarketOrder struct { **Fields description** -* `Sender` field describes the creator of this msg. -* `Order` field describes the order info. +- `Sender` field describes the creator of this msg. +- `Order` field describes the order info. ## Msg/CancelSpotOrder @@ -217,10 +217,10 @@ type MsgCancelSpotOrder struct { **Fields description** -* `Sender` field describes the creator of this msg. -* `MarketId` field describes the id of the market where the order is placed. -* `SubaccountId` field describes the subaccount id that placed the order. -* `OrderHash` field describes the hash of the order. +- `Sender` field describes the creator of this msg. +- `MarketId` field describes the id of the market where the order is placed. +- `SubaccountId` field describes the subaccount id that placed the order. +- `OrderHash` field describes the hash of the order. ## Msg/BatchCancelSpotOrders @@ -235,8 +235,8 @@ type MsgBatchCancelSpotOrders struct { **Fields description** -* `Sender` field describes the creator of this msg. -* `Data` field describes the orders to cancel. +- `Sender` field describes the creator of this msg. +- `Data` field describes the orders to cancel. ## Msg/CreateDerivativeLimitOrder @@ -251,8 +251,8 @@ type MsgCreateDerivativeLimitOrder struct { **Fields description** -* `Sender` field describes the creator of this msg. -* `Order` field describes the order info. +- `Sender` field describes the creator of this msg. +- `Order` field describes the order info. ## Batch creation of derivative limit orders @@ -267,8 +267,8 @@ type MsgBatchCreateDerivativeLimitOrders struct { **Fields description** -* `Sender` field describes the creator of this msg. -* `Orders` field describes the orders info. +- `Sender` field describes the creator of this msg. +- `Orders` field describes the orders info. ## Msg/CreateDerivativeMarketOrder @@ -284,8 +284,8 @@ type MsgCreateDerivativeMarketOrder struct { **Fields description** -* `Sender` field describes the creator of this msg. -* `Order` field describes the order info. +- `Sender` field describes the creator of this msg. +- `Order` field describes the order info. ## Msg/CancelDerivativeOrder @@ -304,10 +304,10 @@ type MsgCancelDerivativeOrder struct { **Fields description** -* `Sender` field describes the creator of this msg. -* `MarketId` field describes the id of the market where the order is placed. -* `SubaccountId` field describes the subaccount id that placed the order. -* `OrderHash` field describes the hash of the order. +- `Sender` field describes the creator of this msg. +- `MarketId` field describes the id of the market where the order is placed. +- `SubaccountId` field describes the subaccount id that placed the order. +- `OrderHash` field describes the hash of the order. ## Msg/BatchCancelDerivativeOrders @@ -322,8 +322,8 @@ type MsgBatchCancelDerivativeOrders struct { **Fields description** -* `Sender` field describes the creator of this msg. -* `Data` field describes the orders to cancel. +- `Sender` field describes the creator of this msg. +- `Data` field describes the orders to cancel. ## Msg/SubaccountTransfer @@ -340,10 +340,10 @@ type MsgSubaccountTransfer struct { **Fields description** -* `Sender` field describes the creator of this msg. -* `SourceSubaccountId` field describes a source subaccount to send coins from. -* `DestinationSubaccountId` field describes a destination subaccount to send coins to. -* `Amount` field describes the amount of coin to send. +- `Sender` field describes the creator of this msg. +- `SourceSubaccountId` field describes a source subaccount to send coins from. +- `DestinationSubaccountId` field describes a destination subaccount to send coins to. +- `Amount` field describes the amount of coin to send. ## Msg/ExternalTransfer @@ -360,10 +360,10 @@ type MsgExternalTransfer struct { **Fields description** -* `Sender` field describes the creator of this msg. -* `SourceSubaccountId` field describes a source subaccount to send coins from. -* `DestinationSubaccountId` field describes a destination subaccount to send coins to. -* `Amount` field describes the amount of coin to send. +- `Sender` field describes the creator of this msg. +- `SourceSubaccountId` field describes a source subaccount to send coins from. +- `DestinationSubaccountId` field describes a destination subaccount to send coins to. +- `Amount` field describes the amount of coin to send. ## Msg/LiquidatePosition @@ -381,10 +381,10 @@ type MsgLiquidatePosition struct { **Fields description** -* `Sender` field describes the creator of this msg. -* `SubaccountId` field describes a subaccount to receive liquidation amount. -* `MarketId` field describes a market where the position is in. -* `Order` field describes the order info. +- `Sender` field describes the creator of this msg. +- `SubaccountId` field describes a subaccount to receive liquidation amount. +- `MarketId` field describes a market where the position is in. +- `Order` field describes the order info. ## Msg/IncreasePositionMargin @@ -404,11 +404,13 @@ type MsgIncreasePositionMargin struct { **Fields description** -* `Sender` field describes the creator of this msg. -* `SourceSubaccountId` field describes a source subaccount to send balance from. -* `DestinationSubaccountId` field describes a destination subaccount to receive balance. -* `MarketId` field describes a market where positions are in. -* `Amount` field describes amount to increase. +- `Sender` field describes the creator of this msg. +- `SourceSubaccountId` field describes a source subaccount to send balance from. +- `DestinationSubaccountId` field describes a destination subaccount to receive balance. +- `MarketId` field describes a market where positions are in. +- `Amount` field describes amount to increase. + + ## Msg/BatchUpdateOrders @@ -431,14 +433,14 @@ type MsgBatchUpdateOrders struct { **Fields description** -* `Sender` field describes the creator of this msg. -* `SubaccountId` field describes the sender's sub-account ID. -* `SpotMarketIdsToCancelAll` field describes a list of spot market IDs for which the sender wants to cancel all open orders. -* `DerivativeMarketIdsToCancelAll` field describes a list of derivative market IDs for which the sender wants to cancel all open orders. -* `SpotOrdersToCancel` field describes specific spot orders the sender wants to cancel. -* `DerivativeOrdersToCancel` field describes specific derivative orders the sender wants to cancel. -* `SpotOrdersToCreate` field describes spot orders the sender wants to create. -* `DerivativeOrdersToCreate` field describes derivative orders the sender wants to create. +- `Sender` field describes the creator of this msg. +- `SubaccountId` field describes the sender's sub-account ID. +- `SpotMarketIdsToCancelAll` field describes a list of spot market IDs for which the sender wants to cancel all open orders. +- `DerivativeMarketIdsToCancelAll` field describes a list of derivative market IDs for which the sender wants to cancel all open orders. +- `SpotOrdersToCancel` field describes specific spot orders the sender wants to cancel. +- `DerivativeOrdersToCancel` field describes specific derivative orders the sender wants to cancel. +- `SpotOrdersToCreate` field describes spot orders the sender wants to create. +- `DerivativeOrdersToCreate` field describes derivative orders the sender wants to create. ## Msg/AuthorizeStakeGrants @@ -453,8 +455,9 @@ type MsgAuthorizeStakeGrants struct { **Fields description** -* `Sender` describes the creator of this msg. -* `Grants` describes a list of grantees' addresses and grant amounts +- `Sender` describes the creator of this msg. +- `Grants` describes a list of grantees' addresses and grant amounts + ## Msg/ActivateStakeGrant @@ -469,5 +472,5 @@ type MsgActivateStakeGrant struct { **Fields description** -* `Sender` describes the creator of this msg. -* `Granter` describes the address of the granter. +- `Sender` describes the creator of this msg. +- `Granter` describes the address of the granter. diff --git a/.gitbook/developers-native/injective/exchange/06_proposals.mdx b/.gitbook/developers-native/injective/exchange/06_proposals.md similarity index 100% rename from .gitbook/developers-native/injective/exchange/06_proposals.mdx rename to .gitbook/developers-native/injective/exchange/06_proposals.md diff --git a/.gitbook/developers-native/injective/exchange/07_begin_block.mdx b/.gitbook/developers-native/injective/exchange/07_begin_block.md similarity index 82% rename from .gitbook/developers-native/injective/exchange/07_begin_block.mdx rename to .gitbook/developers-native/injective/exchange/07_begin_block.md index a73f578..9c682f3 100644 --- a/.gitbook/developers-native/injective/exchange/07_begin_block.mdx +++ b/.gitbook/developers-native/injective/exchange/07_begin_block.md @@ -3,7 +3,7 @@ sidebar_position: 8 title: BeginBlocker --- -# BeginBlock +# BeginBlocker The exchange BeginBlocker runs at the start of every block in our defined order as the last module. @@ -12,7 +12,7 @@ The exchange BeginBlocker runs at the start of every block in our defined order 1. Check the first to receive funding payments market. If the first market is not yet due to receive fundings (funding timestamp not reached), skip all fundings. 2. Otherwise go through each market one by one: 1. Skip market if funding timestamp is not yet reached. - 2. Compute funding as `twap + hourlyInterestRate` where $$twap = \frac{cumulativePrice}{timeInterval * 24}$$ with _timeInterval = lastTimestamp - startingTimestamp_. The `cumulativePrice` is previously calculated with every trade as the time weighted difference between VWAP and mark price: $${\frac{VWAP - markPrice}{markPrice} * timeElapsed}$$ . + 2. Compute funding as `twap + hourlyInterestRate` where $\mathrm{twap = \frac{cumulativePrice}{timeInterval * 24}}$ with $\mathrm{timeInterval = lastTimestamp - startingTimestamp}$. The `cumulativePrice` is previously calculated with every trade as the time weighted difference between VWAP and mark price: $\mathrm{\frac{VWAP - markPrice}{markPrice} * timeElapsed}$. 3. Cap funding if required to the maximum defined by `HourlyFundingRateCap`. 4. Set next funding timestamp. 5. Emit `EventPerpetualMarketFundingUpdate`. @@ -42,22 +42,24 @@ For each time expiry market, iterate through starting with first to expire: 1. Check if the current trading rewards campaign is finished. 2. If the campaign is finished, distribute reward tokens to eligible traders. + 1. Compute the available reward for each reward denom as `min(campaignRewardTokens, communityPoolRewardTokens)` 2. Get the trader rewards based on the trading share from the respective trader calculated as `accountPoints * totalReward / totalTradingRewards`. 3. Send reward tokens from community pool to trader. 4. Reset total and all account trading reward points. 5. Delete the current campaign ending timestamp. + 3. If a new campaign is launched, set the next current campaign ending timestamp as `CurrentCampaignStartTimestamp + CampaignDurationSeconds`. 4. If no current campaign is ongoing and no new campaigns are launched, delete campaign info, market qualifications and market multipliers from storage. ### 5. Process Fee Discount Buckets -* If the oldest bucket's end timestamp is older than the `block.timestamp - bucketCount * bucketDuration`: - * Prune the oldest bucket - * Iterate over all `bucketStartTimestamp + account → FeesPaidAmount`: - * Subtract the `FeesPaidAmount` from each account's `totalPastBucketFeesPaidAmount` - * Delete the account's `account → {tier, TTL timestamp}`. Note that this technically isn't necessary for correctness since we check the TTL timestamps in the Endblocker but is a state pruning strategy. - * Update the `CurrBucketStartTimestamp ← CurrBucketStartTimestamp + BucketDuration`. +- If the oldest bucket's end timestamp is older than the `block.timestamp - bucketCount * bucketDuration`: + - Prune the oldest bucket + - Iterate over all `bucketStartTimestamp + account → FeesPaidAmount`: + - Subtract the `FeesPaidAmount` from each account's `totalPastBucketFeesPaidAmount` + - Delete the account's `account → {tier, TTL timestamp}`. Note that this technically isn't necessary for correctness since we check the TTL timestamps in the Endblocker but is a state pruning strategy. + - Update the `CurrBucketStartTimestamp ← CurrBucketStartTimestamp + BucketDuration`. ``` bucket count 5 and with 100 sec duration diff --git a/.gitbook/developers-native/injective/exchange/08_end_block.mdx b/.gitbook/developers-native/injective/exchange/08_end_block.md similarity index 52% rename from .gitbook/developers-native/injective/exchange/08_end_block.mdx rename to .gitbook/developers-native/injective/exchange/08_end_block.md index e955efa..11131a8 100644 --- a/.gitbook/developers-native/injective/exchange/08_end_block.mdx +++ b/.gitbook/developers-native/injective/exchange/08_end_block.md @@ -3,45 +3,49 @@ sidebar_position: 9 title: EndBlocker --- -# EndBlock +# EndBlocker The exchange EndBlocker runs at the end of every block in our defined order after governance and staking modules, and before the peggy, auction and insurance modules. It is particularly important that the governance module's EndBlocker runs before the exchange module's. -* Stage 0: Determine the fee discounts for all the accounts that have placed an order in a fee-discount supported market in the current block. -* Stage 1: Process all market orders in parallel - spot market and derivative market orders - * Markets orders are executed against the resting orderbook at the time of the beginning of the block. - * Note that market orders may be invalidated in the EndBlocker due to subsequently incoming oracle updates or limit order cancels. -* Stage 2: Persist market order execution to store - * Spot Markets - * Persist Spot market order execution data - * Emit relevant events - * `EventBatchSpotExecution` - * Derivative Markets - * Persist Derivative market order execution data - * Emit relevant events - * `EventBatchDerivativeExecution` - * `EventCancelDerivativeOrder` -* Stage 3: Process all limit orders in parallel - spot and derivative limit orders that are matching - * Limit orders are executed in a frequent batch auction mode to ensure fair matching prices, see below for details. - * Note that vanilla limit orders may be invalidated in the EndBlocker due to subsequently incoming oracle updates and reduce-only limit orders may be invalidated in the EndBlocker due to subsequently incoming orders which flip a position. -* Stage 4: Persist limit order matching execution + new limit orders to store - * Spot Markets - * Persist Spot Matching execution data - * Emit relevant events - * `EventNewSpotOrders` - * `EventBatchSpotExecution` - * Derivative Markets - * Persist Derivative Matching execution data - * Emit relevant events - * `EventNewDerivativeOrders` - * `EventBatchDerivativeExecution` - * `EventCancelDerivativeOrder` -* Stage 5: Persist perpetual market funding info -* Stage 6: Persist trading rewards total and account points. -* Stage 7: Persist new fee discount data, i.e., new fees paid additions and new account tiers. -* Stage 8: Process Spot Market Param Updates if any -* Stage 9: Process Derivative Market Param Updates if any -* Stage 10: Emit Deposit and Position Update Events +- Stage 0: Determine the fee discounts for all the accounts that have placed an order in a fee-discount supported market in the current block. +- Stage 1: Process all market orders in parallel - spot market and derivative market orders + - Markets orders are executed against the resting orderbook at the time of the beginning of the block. + - Note that market orders may be invalidated in the EndBlocker due to subsequently incoming oracle updates or limit order cancels. +- Stage 2: Persist market order execution to store + + - Spot Markets + - Persist Spot market order execution data + - Emit relevant events + - `EventBatchSpotExecution` + - Derivative Markets + - Persist Derivative market order execution data + - Emit relevant events + - `EventBatchDerivativeExecution` + - `EventCancelDerivativeOrder` + +- Stage 3: Process all limit orders in parallel - spot and derivative limit orders that are matching + - Limit orders are executed in a frequent batch auction mode to ensure fair matching prices, see below for details. + - Note that vanilla limit orders may be invalidated in the EndBlocker due to subsequently incoming oracle updates and reduce-only limit orders may be invalidated in the EndBlocker due to subsequently incoming orders which flip a position. +- Stage 4: Persist limit order matching execution + new limit orders to store + + - Spot Markets + - Persist Spot Matching execution data + - Emit relevant events + - `EventNewSpotOrders` + - `EventBatchSpotExecution` + - Derivative Markets + - Persist Derivative Matching execution data + - Emit relevant events + - `EventNewDerivativeOrders` + - `EventBatchDerivativeExecution` + - `EventCancelDerivativeOrder` + +- Stage 5: Persist perpetual market funding info +- Stage 6: Persist trading rewards total and account points. +- Stage 7: Persist new fee discount data, i.e., new fees paid additions and new account tiers. +- Stage 8: Process Spot Market Param Updates if any +- Stage 9: Process Derivative Market Param Updates if any +- Stage 10: Emit Deposit and Position Update Events ## Order Matching: Frequent Batch Auction (FBA) @@ -50,25 +54,25 @@ The goal of FBA is to prevent any [Front-Running](https://www.investopedia.com/t 1. Market orders are filled first against the resting orderbook at the time of the beginning of the block. While the resting orders are filled at their respective order prices, the market orders are all filled at a uniform clearing price with the same mechanism as limit orders. For an example for the market order matching in FBA fashion, look at the API docs [here](https://api.injective.exchange/#examples-market-order-matching). 2. Likewise limit orders are filled at a uniform clearing price. New limit orders are combined with the resting orderbook and orders are matched as long as there is still negative spread. The clearing price is either -a. the best buy/sell order in case the last matched order crosses the spread in that direction, the,\ -b. the mark price in case of derivative markets and the mark price is between the last matched orders or\ +a. the best buy/sell order in case the last matched order crosses the spread in that direction, the, +b. the mark price in case of derivative markets and the mark price is between the last matched orders or c. the mid price. For an example for the limit order matching in FBA fashion, look at the API docs [here](https://api.injective.exchange/#examples-limit-order-matching). ## Single Trade Calculations -* For a qualifying market compute the fee discounts: - * Fee discounts are applied as refunds and the fee paid contribution is recorded. - * Relayer fees are applied AFTER the fee discount is taken. -* For a qualifying market compute the trade reward point contribution: - * Obtain the FeePaidMultiplier for maker and taker. - * Compute the trade reward point contribution. - * Trade reward points are based on the discounted trading fee. -* Calculate fee refunds (or charges). There are several reasons why an order might get a fee refund after matching: +- For a qualifying market compute the fee discounts: + - Fee discounts are applied as refunds and the fee paid contribution is recorded. + - Relayer fees are applied AFTER the fee discount is taken. +- For a qualifying market compute the trade reward point contribution: + - Obtain the FeePaidMultiplier for maker and taker. + - Compute the trade reward point contribution. + - Trade reward points are based on the discounted trading fee. +- Calculate fee refunds (or charges). There are several reasons why an order might get a fee refund after matching: 1. It's a limit order which is not matched or only partially matched which means it will become a resting limit order and switch from a taker to maker fee. The refund is `UnmatchedQuantity * (TakerFeeRate - MakerFeeRate)`. Note that for negative maker fees, we refund the `UnmatchedQuantity * TakerFeeRate` instead. 2. Fee discounts are applied. We refund the difference between the original fee paid and the fee paid after the discount. 3. The order is matched at a better price resulting in a different fee. - * For buy orders a better price means a lower price and thus a lower fee. We refund the fee price delta. - * For sell orders a better price means a higher price and thus a higher fee. We charge the fee price delta. - 4. You can find the respective code with an example [here](https://github.com/InjectiveLabs/injective-core/blob/80dbc4e9558847ff0354be5d19a4d8b0bba7da96/injective-chain/modules/exchange/keeper/derivative_orders_processor.go#L502). Please check the master branch for the latest chain code. + - For buy orders a better price means a lower price and thus a lower fee. We refund the fee price delta. + - For sell orders a better price means a higher price and thus a higher fee. We charge the fee price delta. + - You can find the respective code with an example [here](https://github.com/InjectiveLabs/injective-core/blob/80dbc4e9558847ff0354be5d19a4d8b0bba7da96/injective-chain/modules/exchange/keeper/derivative_orders_processor.go#L502). Please check the master branch for the latest chain code. diff --git a/.gitbook/developers-native/injective/exchange/09_events.mdx b/.gitbook/developers-native/injective/exchange/09_events.md similarity index 100% rename from .gitbook/developers-native/injective/exchange/09_events.mdx rename to .gitbook/developers-native/injective/exchange/09_events.md diff --git a/.gitbook/developers-native/injective/exchange/10_params.mdx b/.gitbook/developers-native/injective/exchange/10_params.md similarity index 100% rename from .gitbook/developers-native/injective/exchange/10_params.mdx rename to .gitbook/developers-native/injective/exchange/10_params.md diff --git a/.gitbook/developers-native/injective/exchange/11_msg_privileged_execute_contract.mdx b/.gitbook/developers-native/injective/exchange/11_msg_privileged_execute_contract.md similarity index 100% rename from .gitbook/developers-native/injective/exchange/11_msg_privileged_execute_contract.mdx rename to .gitbook/developers-native/injective/exchange/11_msg_privileged_execute_contract.md diff --git a/.gitbook/developers-native/injective/exchange/99_errors.mdx b/.gitbook/developers-native/injective/exchange/99_errors.md similarity index 100% rename from .gitbook/developers-native/injective/exchange/99_errors.mdx rename to .gitbook/developers-native/injective/exchange/99_errors.md diff --git a/.gitbook/developers-native/injective/exchange/index.md b/.gitbook/developers-native/injective/exchange/index.md new file mode 100644 index 0000000..d12ad60 --- /dev/null +++ b/.gitbook/developers-native/injective/exchange/index.md @@ -0,0 +1,29 @@ +# `Exchange` + +## Abstract + +The `exchange` module is the heart of the Injective Chain which enables fully decentralized spot and derivative exchange. +It is the _sine qua non_ module of the chain and integrates tightly with the `auction`, `insurance`, `oracle`, and `peggy` modules. + +The exchange protocol enables traders to create and trade on arbitrary spot and derivative markets. +The entire process of orderbook management, trade execution, order matching and settlement occurs on chain through the logic codified by the exchange module. + +The `exchange` module enables the exchange of tokens on two types of markets: + +1. `Derivative Market`: Either a `Perpetual Swap Market` or a `Futures Market`. +2. `Spot Market` + +## Contents + +1. [Derivative Market Concepts](./00_derivative_market_concepts.md) +2. [Spot Market Concepts](./01_spot_market_concepts.md) +3. [Other Concepts](./02_other_concepts.md) +4. [State](./03_state.md) +5. [State Transitions](./04_state_transitions.md) +6. [Messages](./05_messages.md) +7. [Proposals](./06_proposals.md) +8. [Begin Block](./07_begin_block.md) +9. [End Block](./08_end_block.md) +10. [Events](./09_events.md) +11. [Params](./10_params.md) +12. [MsgPrivilegedExecuteContract](./11_msg_privileged_execute_contract.md) diff --git a/.gitbook/developers-native/injective/index.md b/.gitbook/developers-native/injective/index.md new file mode 100644 index 0000000..dd7ea83 --- /dev/null +++ b/.gitbook/developers-native/injective/index.md @@ -0,0 +1,3 @@ +# Injective + +## Injective Modules diff --git a/.gitbook/developers-native/injective/insurance/01_state.mdx b/.gitbook/developers-native/injective/insurance/01_state.md similarity index 94% rename from .gitbook/developers-native/injective/insurance/01_state.mdx rename to .gitbook/developers-native/injective/insurance/01_state.md index f36b97f..b7c3402 100644 --- a/.gitbook/developers-native/injective/insurance/01_state.mdx +++ b/.gitbook/developers-native/injective/insurance/01_state.md @@ -9,7 +9,7 @@ title: State `Params` is a module-wide configuration structure that stores system parameters and defines overall functioning of the insurance module. -* Params: `Paramsspace("insurance") -> legacy_amino(params)` +- Params: `Paramsspace("insurance") -> legacy_amino(params)` ```go @@ -70,7 +70,7 @@ type RedemptionSchedule struct { } ``` -Additionally, we introduce `next_share_denom_id` and `next_redemption_schedule_id` to manage insurance fund share token\ +Additionally, we introduce `next_share_denom_id` and `next_redemption_schedule_id` to manage insurance fund share token denom and redemption schedules from various users. ```go @@ -87,5 +87,6 @@ type GenesisState struct { ## Pending Redemptions -Pending Redemptions Objects are kept to store all the information about redemption requests and to auto-withdraw when\ +Pending Redemptions Objects are kept to store all the information about redemption requests and to auto-withdraw when the duration pass. + diff --git a/.gitbook/developers-native/injective/insurance/02_state_transitions.md b/.gitbook/developers-native/injective/insurance/02_state_transitions.md new file mode 100644 index 0000000..08b66df --- /dev/null +++ b/.gitbook/developers-native/injective/insurance/02_state_transitions.md @@ -0,0 +1,124 @@ +--- +sidebar_position: 2 +title: State Transitions +--- + +# State Transitions + +This document describes the state transition operations pertaining to: + +- Creating an insurance fund +- Underwriting an insurance fund +- Request a redemption from the insurance fund +- Automatic processing of matured redemption requests + +## Creating insurance fund + +**Params description** +`Sender` field describes the creator of an insurance fund . +`Ticker`, `QuoteDenom`, `OracleBase`, `OracleQuote`, `OracleType`, `Expiry` fields describe the derivative market info +that the insurance fund associated to. +`InitialDeposit` field describes the initial deposit amount to be put on the insurance fund. + +**Steps** + +- Get `MarketId` for the insurance fund - **Note**, market could be not available yet on `exchange` and it's not an + issue +- Ensure if insurance fund associated to the `MarketId` does not exist +- Ensure if initial deposit amount is not zero +- Get `shareDenom` that is unique - it's incremented when share denom is requested for insurance fund creation or when + underwriting insurance fund that has zero balance and non-zero total share denom supply. +- Send coins from creator's account to insurance fund module account +- Create insurance fund object with `DefaultRedemptionNoticePeriodDuration` and with the params provided +- Set `Balance` of fund object to initial deposit amount +- Mint `InsuranceFundInitialSupply` (10^18) `shareDenom` tokens to creator account +- Save insurance fund object to store +- Register newly created insurance fund `shareDenom` metadata inside BankKeeper + +## Underwriting an insurance fund + +**Params description** +`Sender` field describes the underwriter of an insurance fund . +`MarketId` field describes the derivative market id to the insurance fund. +`Deposit` field describes the deposit amount to be added on the insurance fund. + +**Steps** + +- Ensure if insurance fund associated to the `MarketId` does exist +- Send underwriting tokens from sender's account to module account +- Make actions based on the status of insurance fund associated to the `MarketId`. + * A. when `Balance` and `ShareDenomSupply` are zero + 1. mint `InsuranceFundInitialSupply` (10^18) to the sender. + 2. set `Balance` to deposit amount + 3. set `ShareDenomSupply` to `InsuranceFundInitialSupply` + * B. when `Balance` is zero and `ShareDenomSupply` is not zero + 1. change `ShareDenom` of the the insurance fund to start new insurance fund from beginning. + 2. register newly created `ShareDenom` in bank keeper + 3. mint `InsuranceFundInitialSupply` (10^18) to the sender. + 4. set `Balance` to deposit amount + 5. set `ShareDenomSupply` to `InsuranceFundInitialSupply` + * C. when `Balance` is not zero and `ShareDenomSupply` is zero + 1. mint `InsuranceFundInitialSupply` (10^18) to the sender. + 2. increase `Balance` by deposit amount + 3. set `ShareDenomSupply` to `InsuranceFundInitialSupply` + * D. when both `Balance` and `ShareDenomSupply` are not zero - normal case + 1. increase `Balance` by deposit amount + 2. mint `prev_ShareDenomSupply * deposit_amount / prev_Balance` amount of `ShareDenom` to sender + 3. increase `ShareDenomSupply` with mint amount +- Save insurance fund object to store + +## Requesting a redemption from an insurance fund + +**Params description** +`Sender` field describes the redemption requester of an insurance fund . +`MarketId` field describes the derivative market id associated to the insurance fund. +`Amount` field describes the share token amount to be redeemed. + +**Steps** + +- Ensure insurance fund associated to the `MarketId` does exist +- Send `ShareDenom` to module account +- Get new redemption schedule ID +- Calculate `ClaimTime` from insurance fund's redemption notice period duration and current block time +- Calculate key to store pending redemption (redemption schedule) +- Create redemption schedule object with details +- Store redemption schedule object to store + +## Insurance fund actions on liquidation events in derivative market + +**Steps** + +- `exchange` module finds relative insurance fund from the insurance keeper. +- if `missingFund` is positive, it withdraws the amount from the insurance fund through `WithdrawFromInsuranceFund`. +- if `missingFund` is negative, it deposits the amount into the insurance fund through `DepositIntoInsuranceFund`. + +## Automatic processing of pending redemptions + +**Steps** + +Iterate all matured redemptions by sorted order by `ClaimTime` and perform the following actions: + +- If `ClaimTime` is after current block time, break early +- Ensure the insurance fund exist for matured redemption schedule +- Calculate redeem amount from share amount - `shareAmt * fund.Balance * fund.TotalShare` +- Send calculate redeem amount from module account to redeemer account +- Burn share tokens sent to the module account at the time of redemption schedule +- Delete redemption schedule object +- Reduce insurance fund's `Balance` by redeem amount +- Store updated insurance object to store + +# Hooks + +Other modules may register operations to execute when a certain event has occurred within insurance fund. These events +can be registered to execute either right `Before` or `After` the exchange event (as per the hook name). The following +hooks can registered with the exchange: + +**Note**: Hooks are not available and exchange module calls insurance keeper function directly. + +**Steps** +When liquidation event happen in derivative market + +- `exchange` module finds relative insurance fund from the insurance keeper. +- if `missingFund` is positive, it withdraws the amount from the insurance fund through `WithdrawFromInsuranceFund`. +- if `missingFund` is negative, it deposits the amount into the insurance fund through `DepositIntoInsuranceFund`. + diff --git a/.gitbook/developers-native/injective/insurance/02_state_transitions.mdx b/.gitbook/developers-native/injective/insurance/02_state_transitions.mdx deleted file mode 100644 index 34c6b80..0000000 --- a/.gitbook/developers-native/injective/insurance/02_state_transitions.mdx +++ /dev/null @@ -1,116 +0,0 @@ ---- -sidebar_position: 2 -title: State Transitions ---- - -# State Transitions - -## State Transitions - -This document describes the state transition operations pertaining to: - -* Creating an insurance fund -* Underwriting an insurance fund -* Request a redemption from the insurance fund -* Automatic processing of matured redemption requests - -### Creating insurance fund - -**Params description**`Sender` field describes the creator of an insurance fund .`Ticker`, `QuoteDenom`, `OracleBase`, `OracleQuote`, `OracleType`, `Expiry` fields describe the derivative market info\ -that the insurance fund associated to.`InitialDeposit` field describes the initial deposit amount to be put on the insurance fund. - -**Steps** - -* Get `MarketId` for the insurance fund - **Note**, market could be not available yet on `exchange` and it's not an\ - issue -* Ensure if insurance fund associated to the `MarketId` does not exist -* Ensure if initial deposit amount is not zero -* Get `shareDenom` that is unique - it's incremented when share denom is requested for insurance fund creation or when\ - underwriting insurance fund that has zero balance and non-zero total share denom supply. -* Send coins from creator's account to insurance fund module account -* Create insurance fund object with `DefaultRedemptionNoticePeriodDuration` and with the params provided -* Set `Balance` of fund object to initial deposit amount -* Mint `InsuranceFundInitialSupply` (10^18) `shareDenom` tokens to creator account -* Save insurance fund object to store -* Register newly created insurance fund `shareDenom` metadata inside BankKeeper - -### Underwriting an insurance fund - -**Params description**`Sender` field describes the underwriter of an insurance fund .`MarketId` field describes the derivative market id to the insurance fund.`Deposit` field describes the deposit amount to be added on the insurance fund. - -**Steps** - -* Ensure if insurance fund associated to the `MarketId` does exist -* Send underwriting tokens from sender's account to module account -* Make actions based on the status of insurance fund associated to the `MarketId`. - * A. when `Balance` and `ShareDenomSupply` are zero - 1. mint `InsuranceFundInitialSupply` (10^18) to the sender. - 2. set `Balance` to deposit amount - 3. set `ShareDenomSupply` to `InsuranceFundInitialSupply` - * B. when `Balance` is zero and `ShareDenomSupply` is not zero - 1. change `ShareDenom` of the the insurance fund to start new insurance fund from beginning. - 2. register newly created `ShareDenom` in bank keeper - 3. mint `InsuranceFundInitialSupply` (10^18) to the sender. - 4. set `Balance` to deposit amount - 5. set `ShareDenomSupply` to `InsuranceFundInitialSupply` - * C. when `Balance` is not zero and `ShareDenomSupply` is zero - 1. mint `InsuranceFundInitialSupply` (10^18) to the sender. - 2. increase `Balance` by deposit amount - 3. set `ShareDenomSupply` to `InsuranceFundInitialSupply` - * D. when both `Balance` and `ShareDenomSupply` are not zero - normal case - 1. increase `Balance` by deposit amount - 2. mint `prev_ShareDenomSupply * deposit_amount / prev_Balance` amount of `ShareDenom` to sender - 3. increase `ShareDenomSupply` with mint amount -* Save insurance fund object to store - -### Requesting a redemption from an insurance fund - -**Params description**`Sender` field describes the redemption requester of an insurance fund .`MarketId` field describes the derivative market id associated to the insurance fund.`Amount` field describes the share token amount to be redeemed. - -**Steps** - -* Ensure insurance fund associated to the `MarketId` does exist -* Send `ShareDenom` to module account -* Get new redemption schedule ID -* Calculate `ClaimTime` from insurance fund's redemption notice period duration and current block time -* Calculate key to store pending redemption (redemption schedule) -* Create redemption schedule object with details -* Store redemption schedule object to store - -### Insurance fund actions on liquidation events in derivative market - -**Steps** - -* `exchange` module finds relative insurance fund from the insurance keeper. -* if `missingFund` is positive, it withdraws the amount from the insurance fund through `WithdrawFromInsuranceFund`. -* if `missingFund` is negative, it deposits the amount into the insurance fund through `DepositIntoInsuranceFund`. - -### Automatic processing of pending redemptions - -**Steps** - -Iterate all matured redemptions by sorted order by `ClaimTime` and perform the following actions: - -* If `ClaimTime` is after current block time, break early -* Ensure the insurance fund exist for matured redemption schedule -* Calculate redeem amount from share amount - `shareAmt * fund.Balance * fund.TotalShare` -* Send calculate redeem amount from module account to redeemer account -* Burn share tokens sent to the module account at the time of redemption schedule -* Delete redemption schedule object -* Reduce insurance fund's `Balance` by redeem amount -* Store updated insurance object to store - -## Hooks - -Other modules may register operations to execute when a certain event has occurred within insurance fund. These events\ -can be registered to execute either right `Before` or `After` the exchange event (as per the hook name). The following\ -hooks can registered with the exchange: - -**Note**: Hooks are not available and exchange module calls insurance keeper function directly. - -**Steps**\ -When liquidation event happen in derivative market - -* `exchange` module finds relative insurance fund from the insurance keeper. -* if `missingFund` is positive, it withdraws the amount from the insurance fund through `WithdrawFromInsuranceFund`. -* if `missingFund` is negative, it deposits the amount into the insurance fund through `DepositIntoInsuranceFund`. diff --git a/.gitbook/developers-native/injective/insurance/03_messages.mdx b/.gitbook/developers-native/injective/insurance/03_messages.md similarity index 81% rename from .gitbook/developers-native/injective/insurance/03_messages.mdx rename to .gitbook/developers-native/injective/insurance/03_messages.md index ece8e69..c91541c 100644 --- a/.gitbook/developers-native/injective/insurance/03_messages.mdx +++ b/.gitbook/developers-native/injective/insurance/03_messages.md @@ -5,7 +5,7 @@ title: Messages # Messages -In this section we describe the processing of the exchange messages and the corresponding updates to the state. All created/modified state objects specified by each message are defined within the [state](02_state_transitions.md) section. +In this section we describe the processing of the exchange messages and the corresponding updates to the state. All created/modified state objects specified by each message are defined within the [state](./02_state_transitions.md) section. ## Msg/CreateInsuranceFund @@ -37,14 +37,14 @@ message MsgCreateInsuranceFund { **Fields description** -* `Sender` field describes the creator of an insurance fund . -* `Ticker`, `QuoteDenom`, `OracleBase`, `OracleQuote`, `OracleType`, `Expiry` fields describe the derivative market info\ +- `Sender` field describes the creator of an insurance fund . +- `Ticker`, `QuoteDenom`, `OracleBase`, `OracleQuote`, `OracleType`, `Expiry` fields describe the derivative market info that the insurance fund corresponds to. -* `InitialDeposit` specifies the initial deposit amount used to underwrite the insurance fund. +- `InitialDeposit` specifies the initial deposit amount used to underwrite the insurance fund. Disclaimer: When creating an insurance fund a small portion of shares (1%) will be reserved by the fund itself (protocol owned liquidity). A value of 1 USD is recommended as first subscription. -Motivation behind this feature is to avoid potential rounding issues when underwriting to a fund. For example, without having protocol owned liquidity, if the original fund creator would take out most of their shares leaving but a small amount, the value of the share token could diverge drastically from the original value. The next underwriter would then have to provide a much larger deposit despite gaining the same amount of shares. +Motivation behind this feature is to avoid potential rounding issues when underwriting to a fund. For example, without having protocol owned liquidity, if the original fund creator would take out most of their shares leaving but a small amount, the value of the share token could diverge drastically from the original value. The next underwriter would then have to provide a much larger deposit despite gaining the same amount of shares. ## Msg/Underwrite @@ -66,9 +66,9 @@ message MsgUnderwrite { **Fields description** -* `Sender` field describes the underwriter of an insurance fund . -* `MarketId` field describes the derivative market id to the insurance fund. -* `Deposit` field describes the deposit amount to be added on the insurance fund. +- `Sender` field describes the underwriter of an insurance fund . +- `MarketId` field describes the derivative market id to the insurance fund. +- `Deposit` field describes the deposit amount to be added on the insurance fund. ## Msg/RequestRedemption @@ -90,6 +90,6 @@ message MsgRequestRedemption { **Fields description** -* `Sender` field describes the redemption requester of an insurance fund . -* `MarketId` field describes the derivative market id associated to the insurance fund. -* `Amount` field describes the share token amount to be redeemed. +- `Sender` field describes the redemption requester of an insurance fund . +- `MarketId` field describes the derivative market id associated to the insurance fund. +- `Amount` field describes the share token amount to be redeemed. diff --git a/.gitbook/developers-native/injective/insurance/04_end_block.mdx b/.gitbook/developers-native/injective/insurance/04_end_block.md similarity index 100% rename from .gitbook/developers-native/injective/insurance/04_end_block.mdx rename to .gitbook/developers-native/injective/insurance/04_end_block.md diff --git a/.gitbook/developers-native/injective/insurance/05_events.mdx b/.gitbook/developers-native/injective/insurance/05_events.md similarity index 100% rename from .gitbook/developers-native/injective/insurance/05_events.mdx rename to .gitbook/developers-native/injective/insurance/05_events.md diff --git a/.gitbook/developers-native/injective/insurance/06_params.mdx b/.gitbook/developers-native/injective/insurance/06_params.md similarity index 100% rename from .gitbook/developers-native/injective/insurance/06_params.mdx rename to .gitbook/developers-native/injective/insurance/06_params.md diff --git a/.gitbook/developers-native/injective/insurance/07_future_improvements.mdx b/.gitbook/developers-native/injective/insurance/07_future_improvements.md similarity index 100% rename from .gitbook/developers-native/injective/insurance/07_future_improvements.mdx rename to .gitbook/developers-native/injective/insurance/07_future_improvements.md diff --git a/.gitbook/developers-native/injective/insurance/99_errors.mdx b/.gitbook/developers-native/injective/insurance/99_errors.md similarity index 100% rename from .gitbook/developers-native/injective/insurance/99_errors.mdx rename to .gitbook/developers-native/injective/insurance/99_errors.md diff --git a/.gitbook/developers-native/injective/insurance.mdx b/.gitbook/developers-native/injective/insurance/index.md similarity index 77% rename from .gitbook/developers-native/injective/insurance.mdx rename to .gitbook/developers-native/injective/insurance/index.md index 711effa..0769922 100644 --- a/.gitbook/developers-native/injective/insurance.mdx +++ b/.gitbook/developers-native/injective/insurance/index.md @@ -10,10 +10,10 @@ Each insurance fund grows when positions in its corresponding derivative market ## Contents -1. [State](01_state.md) -2. [State Transitions](02_state_transitions.md) -3. [Messages](03_messages.md) -4. [End Block](04_end_block.md) -5. [Events](05_events.md) -6. [Params](06_params.md) -7. [Future Improvements](07_future_improvements.md) +1. [State](./01_state.md) +2. [State Transitions](./02_state_transitions.md) +3. [Messages](./03_messages.md) +4. [End Block](./04_end_block.md) +5. [Events](./05_events.md) +6. [Params](./06_params.md) +7. [Future Improvements](./07_future_improvements.md) diff --git a/.gitbook/developers-native/injective/lanes.mdx b/.gitbook/developers-native/injective/lanes/index.md similarity index 81% rename from .gitbook/developers-native/injective/lanes.mdx rename to .gitbook/developers-native/injective/lanes/index.md index 5f31893..53aeea3 100644 --- a/.gitbook/developers-native/injective/lanes.mdx +++ b/.gitbook/developers-native/injective/lanes/index.md @@ -1,19 +1,20 @@ -# Lanes +# Injective Block SDK Integration Injective integrates the [Block SDK](https://github.com/InjectiveLabs/block-sdk). Our solution leverages a multi‑lane mempool that separates transactions into four distinct lanes: -* **Oracle Lane** – for transactions that contain oracle messages. -* **Governance Lane** – for any transaction sent by an admin of the exchange module. -* **Exchange Lane** – for transactions that contain only exchange messages. -* **Default Lane** – for all other transactions. +- **Oracle Lane** – for transactions that contain oracle messages. +- **Governance Lane** – for any transaction sent by an admin of the exchange module. +- **Exchange Lane** – for transactions that contain only exchange messages. +- **Default Lane** – for all other transactions. ## Key Features ### 1. Multi‑Lane Mempool -* **Priority Ordering:**\ +- **Priority Ordering:** The lanes are ordered by priority: the Oracle Lane has the highest priority, followed by the Governance Lane, then the Exchange Lane, and finally the Default Lane. This ordering is critical when building and verifying block proposals. -* **Dedicated Lane Logic:**\ + +- **Dedicated Lane Logic:** Each lane uses its own match handler. We have the following lanes in order of priority: 1. The **Oracle Lane** checks that the transaction contains an oracle message. 2. The **Governance Lane** checks that the first signer is an admin of the exchange module. @@ -24,9 +25,10 @@ Injective integrates the [Block SDK](https://github.com/InjectiveLabs/block-sdk) A key enhancement in our integration is the custom logic for routing transactions based on priority. -* **If a transaction from the same signer already exists in a lane with lower priority:**\ +- **If a transaction from the same signer already exists in a lane with lower priority:** The match handler returns `false`, meaning the new transaction is not captured by the current (higher‑priority) lane. Instead, it falls through to be processed by the lower‑priority lane. -* **Otherwise:**\ + +- **Otherwise:** The new transaction is accepted in the current lane. This mechanism prevents account sequence mismatches. **As a user, you need to be aware that prior lower‑priority transactions may be processed first, even if you submit a new transaction with higher priority. Further, they might cause delays in processing your new transaction.** @@ -35,16 +37,17 @@ This mechanism prevents account sequence mismatches. **As a user, you need to be The Exchange Lane uses custom priority logic to order transactions based on fee discounts, account tiers, and special handling for liquidation messages. Key points include: -* **Custom Tx Priority Calculation:**\ +- **Custom Tx Priority Calculation:** The Exchange Lane extracts the transaction’s priority by considering the account’s fee discount tier and, if applicable, whether the transaction contains only liquidation messages. Liquidation messages are assigned highest priority. -* **Account Tier and Fee Discount:**\ + +- **Account Tier and Fee Discount:** For regular exchange transactions, the lane computes the highest account tier (from the transaction’s signer data) as a measure of priority. Higher tiers result in higher priority. ### 4. Oracle and Governance Lane Max Gas Limit -Transactions that exceed the max gas limit of the Oracle and Governance Lanes\ -are rejected in the `matching` stage (when a tx is inserted in the mempool). If\ -we didn't do this in the matching stage, a big transaction could make it into the\ -lane, and be rejected later in the `prepare` stage (in PrepareProposal). The\ -transaction would remain in the mempool indefinitely, thereby blocking the sender\ +Transactions that exceed the max gas limit of the Oracle and Governance Lanes +are rejected in the `matching` stage (when a tx is inserted in the mempool). If +we didn't do this in the matching stage, a big transaction could make it into the +lane, and be rejected later in the `prepare` stage (in PrepareProposal). The +transaction would remain in the mempool indefinitely, thereby blocking the sender account from submitting any other transactions. diff --git a/.gitbook/developers-native/injective/ocr/01_concepts.mdx b/.gitbook/developers-native/injective/ocr/01_concepts.md similarity index 100% rename from .gitbook/developers-native/injective/ocr/01_concepts.mdx rename to .gitbook/developers-native/injective/ocr/01_concepts.md diff --git a/.gitbook/developers-native/injective/ocr/02_state.mdx b/.gitbook/developers-native/injective/ocr/02_state.md similarity index 98% rename from .gitbook/developers-native/injective/ocr/02_state.mdx rename to .gitbook/developers-native/injective/ocr/02_state.md index 467ad0e..5ab39bb 100644 --- a/.gitbook/developers-native/injective/ocr/02_state.mdx +++ b/.gitbook/developers-native/injective/ocr/02_state.md @@ -30,14 +30,12 @@ type GenesisState struct { PendingPayeeships []*PendingPayeeship } ``` - ## Params -`Params` is a module-wide configuration that stores system parameters and defines overall functioning of the ocr module.\ +`Params` is a module-wide configuration that stores system parameters and defines overall functioning of the ocr module. This module is modifiable by governance using params update proposal natively supported by `gov` module. Struct for the `ocr` module params store. - ```go type Params struct { // Native denom for LINK coin in the bank keeper @@ -177,7 +175,6 @@ type ContractConfig struct { OffchainConfig []byte } ``` - ### FeedProperties `FeedProperties` is a unit to store the properties of feed by id. @@ -209,7 +206,7 @@ type FeedProperties struct { ### PendingPayeeship -`PendingPayeeship` is a record that is stored when a person is delegating payeeship to another address.\ +`PendingPayeeship` is a record that is stored when a person is delegating payeeship to another address. When proposed payee accept this, this record is removed. ```go @@ -218,4 +215,4 @@ type PendingPayeeship struct { Transmitter string ProposedPayee string } -``` +``` \ No newline at end of file diff --git a/.gitbook/developers-native/injective/ocr/03_messages.mdx b/.gitbook/developers-native/injective/ocr/03_messages.md similarity index 100% rename from .gitbook/developers-native/injective/ocr/03_messages.mdx rename to .gitbook/developers-native/injective/ocr/03_messages.md diff --git a/.gitbook/developers-native/injective/ocr/04_proposals.mdx b/.gitbook/developers-native/injective/ocr/04_proposals.md similarity index 100% rename from .gitbook/developers-native/injective/ocr/04_proposals.mdx rename to .gitbook/developers-native/injective/ocr/04_proposals.md diff --git a/.gitbook/developers-native/injective/ocr/05_begin_block.mdx b/.gitbook/developers-native/injective/ocr/05_begin_block.md similarity index 100% rename from .gitbook/developers-native/injective/ocr/05_begin_block.mdx rename to .gitbook/developers-native/injective/ocr/05_begin_block.md diff --git a/.gitbook/developers-native/injective/ocr/06_hooks.md b/.gitbook/developers-native/injective/ocr/06_hooks.md new file mode 100644 index 0000000..c50e2ac --- /dev/null +++ b/.gitbook/developers-native/injective/ocr/06_hooks.md @@ -0,0 +1,17 @@ +--- +sidebar_position: 6 +--- + +# Hooks + +Other modules may register operations to execute when a certain event has occurred within ocr module. The following hooks can registered with ocr: + +- `AfterSetFeedConfig(ctx sdk.Context, feedConfig *FeedConfig)` + - called after feed config is created or updated +- `AfterTransmit(ctx sdk.Context, feedId string, answer math.LegacyDec, timestamp int64)` + - called when info is transmitted +- `AfterFundFeedRewardPool(ctx sdk.Context, feedId string, newPoolAmount sdk.Coin)` + - called when feed reward pool is updated + +Note: +`oracle` module is accepting `AfterTransmit` hook to store cumulative price when transmission is made. \ No newline at end of file diff --git a/.gitbook/developers-native/injective/ocr/06_hooks.mdx b/.gitbook/developers-native/injective/ocr/06_hooks.mdx deleted file mode 100644 index 74d4ffd..0000000 --- a/.gitbook/developers-native/injective/ocr/06_hooks.mdx +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_position: 6 ---- - -# Hooks - -Other modules may register operations to execute when a certain event has occurred within ocr module. The following hooks can registered with ocr: - -* `AfterSetFeedConfig(ctx sdk.Context, feedConfig *FeedConfig)` - * called after feed config is created or updated -* `AfterTransmit(ctx sdk.Context, feedId string, answer math.LegacyDec, timestamp int64)` - * called when info is transmitted -* `AfterFundFeedRewardPool(ctx sdk.Context, feedId string, newPoolAmount sdk.Coin)` - * called when feed reward pool is updated - -Note:`oracle` module is accepting `AfterTransmit` hook to store cumulative price when transmission is made. diff --git a/.gitbook/developers-native/injective/ocr/07_events.mdx b/.gitbook/developers-native/injective/ocr/07_events.md similarity index 85% rename from .gitbook/developers-native/injective/ocr/07_events.mdx rename to .gitbook/developers-native/injective/ocr/07_events.md index 68c89f2..257d2c9 100644 --- a/.gitbook/developers-native/injective/ocr/07_events.mdx +++ b/.gitbook/developers-native/injective/ocr/07_events.md @@ -89,11 +89,14 @@ The ocr module emits the following events: ### SetBatchConfigProposal -| Type | Attribute Key | Attribute Value | -| ----------------- | ------------------------- | --------------------------- | -| EventConfigSet\[] | ConfigDigest | {ConfigDigest} | -| EventConfigSet\[] | PreviousConfigBlockNumber | {PreviousConfigBlockNumber} | -| EventConfigSet\[] | Config | {Config} | -| EventConfigSet\[] | ConfigInfo | {ConfigInfo} | +| Type | Attribute Key | Attribute Value | +| ---------------- | ------------------------- | --------------------------- | +| EventConfigSet[] | ConfigDigest | {ConfigDigest} | +| EventConfigSet[] | PreviousConfigBlockNumber | {PreviousConfigBlockNumber} | +| EventConfigSet[] | Config | {Config} | +| EventConfigSet[] | ConfigInfo | {ConfigInfo} | ## BeginBlocker + +| Type | Attribute Key | Attribute Value | +| ---- | ------------- | --------------- | diff --git a/.gitbook/developers-native/injective/ocr/08_params.mdx b/.gitbook/developers-native/injective/ocr/08_params.md similarity index 100% rename from .gitbook/developers-native/injective/ocr/08_params.mdx rename to .gitbook/developers-native/injective/ocr/08_params.md diff --git a/.gitbook/developers-native/injective/ocr/99_errors.mdx b/.gitbook/developers-native/injective/ocr/99_errors.md similarity index 100% rename from .gitbook/developers-native/injective/ocr/99_errors.mdx rename to .gitbook/developers-native/injective/ocr/99_errors.md diff --git a/.gitbook/developers-native/injective/ocr.mdx b/.gitbook/developers-native/injective/ocr/index.md similarity index 58% rename from .gitbook/developers-native/injective/ocr.mdx rename to .gitbook/developers-native/injective/ocr/index.md index 2d4eb61..1d92a27 100644 --- a/.gitbook/developers-native/injective/ocr.mdx +++ b/.gitbook/developers-native/injective/ocr/index.md @@ -1,21 +1,21 @@ -# OCR +# Ocr ## Abstract OCR module is to store chainlink's OCR(Off-Chain Report) info into the chain storage. -Feed configuration is managed by module admin and report move to on-chain by transmitters and observers.\ +Feed configuration is managed by module admin and report move to on-chain by transmitters and observers. Transmitters and observers are rewarded in LINK token on the chain configured by governance. While storing feed information, module provide hooks where oracle module can use for the calculation of cumulative price for futures market. ## Contents -1. [Concepts](01_concepts.md) -2. [State](02_state.md) -3. [Messages](03_messages.md) -4. [Proposals](04_proposals.md) -5. [Begin-Block](05_begin_block.md) -6. [Hooks](06_hooks.md) -7. [Events](07_events.md) -8. [Parameters](08_params.md) +1. [Concepts](./01_concepts.md) +2. [State](./02_state.md) +3. [Messages](./03_messages.md) +4. [Proposals](./04_proposals.md) +5. [Begin-Block](./05_begin_block.md) +6. [Hooks](./06_hooks.md) +7. [Events](./07_events.md) +8. [Parameters](./08_params.md) diff --git a/.gitbook/developers-native/injective/oracle/01_state.mdx b/.gitbook/developers-native/injective/oracle/01_state.md similarity index 100% rename from .gitbook/developers-native/injective/oracle/01_state.mdx rename to .gitbook/developers-native/injective/oracle/01_state.md diff --git a/.gitbook/developers-native/injective/oracle/02_keeper.mdx b/.gitbook/developers-native/injective/oracle/02_keeper.md similarity index 95% rename from .gitbook/developers-native/injective/oracle/02_keeper.mdx rename to .gitbook/developers-native/injective/oracle/02_keeper.md index d9508b1..32509c5 100644 --- a/.gitbook/developers-native/injective/oracle/02_keeper.mdx +++ b/.gitbook/developers-native/injective/oracle/02_keeper.md @@ -3,16 +3,16 @@ sidebar_position: 2 title: Keepers --- -# Keeper +# Keepers -The oracle module currently provides three different exported keeper interfaces which can be passed to other modules\ -which need to read price feeds. Modules should use the least-permissive interface which provides the functionality they\ +The oracle module currently provides three different exported keeper interfaces which can be passed to other modules +which need to read price feeds. Modules should use the least-permissive interface which provides the functionality they require. ## Oracle Module ViewKeeper -The oracle module ViewKeeper provides the ability to obtain price data as well as cumulative price data for any\ -supported oracle type and oracle pair. +The oracle module ViewKeeper provides the ability to obtain price data as well as cumulative price data for any +supported oracle type and oracle pair. ```go type ViewKeeper interface { @@ -21,7 +21,7 @@ type ViewKeeper interface { } ``` -Note that the `GetPrice` for Coinbase oracles returns the 5 minute TWAP price. +Note that the `GetPrice` for Coinbase oracles returns the 5 minute TWAP price. ## Band @@ -77,7 +77,7 @@ type CoinbaseKeeper interface { } ``` -The `GetCoinbasePrice` returns the 5 minute TWAP price of the CoinbasePriceState based off the `CoinbasePriceState.Timestamp` values provided by Coinbase. +The `GetCoinbasePrice` returns the 5 minute TWAP price of the CoinbasePriceState based off the `CoinbasePriceState.Timestamp` values provided by Coinbase. ## PriceFeeder @@ -117,5 +117,4 @@ type StorkKeeper interface { GetAllStorkPriceStates(ctx sdk.Context) []*types.StorkPriceState } ``` - -The GetStorkPrice returns the price(`value`) of the StorkPriceState. +The GetStorkPrice returns the price(`value`) of the StorkPriceState. \ No newline at end of file diff --git a/.gitbook/developers-native/injective/oracle/03_messages.mdx b/.gitbook/developers-native/injective/oracle/03_messages.md similarity index 90% rename from .gitbook/developers-native/injective/oracle/03_messages.mdx rename to .gitbook/developers-native/injective/oracle/03_messages.md index 3adf528..599e47a 100644 --- a/.gitbook/developers-native/injective/oracle/03_messages.mdx +++ b/.gitbook/developers-native/injective/oracle/03_messages.md @@ -7,8 +7,9 @@ title: Messages ## MsgRelayBandRates -Authorized Band relayers can relay price feed data for multiple symbols with the `MsgRelayBandRates` message.\ -The registered handler iterates over all the symbols present in the `MsgRelayBandRates` and creates/updates the`BandPriceState` for each symbol. +Authorized Band relayers can relay price feed data for multiple symbols with the `MsgRelayBandRates` message. +The registered handler iterates over all the symbols present in the `MsgRelayBandRates` and creates/updates the +`BandPriceState` for each symbol. ```protobuf message MsgRelayBandRates { @@ -81,12 +82,12 @@ message MsgRequestBandIBCRates { } ``` -Anyone can broadcast this message and no specific authorization is needed.\ +Anyone can broadcast this message and no specific authorization is needed. The handler checks if `BandIbcEnabled` flag is true and go ahead sending a request. ## MsgRelayPythPrices -`MsgRelayPythPrices` is a message for the Pyth contract relay prices to the oracle module. +`MsgRelayPythPrices` is a message for the Pyth contract relay prices to the oracle module. ```protobuf // MsgRelayPythPrices defines a SDK message for updating Pyth prices @@ -125,12 +126,12 @@ enum PythStatus { } ``` -This message is expected to fail if the Relayer (`sender`) does not equal the Pyth contract address as defined in the\ -oracle module Params. +This message is expected to fail if the Relayer (`sender`) does not equal the Pyth contract address as defined in the +oracle module Params. ## MsgRelayStorkPrices -`MsgRelayStorkPrices` is a message for the Stork contract relay prices to the oracle module. +`MsgRelayStorkPrices` is a message for the Stork contract relay prices to the oracle module. ```protobuf // MsgRelayStorkPrices defines a SDK message for relaying price message from Stork API. @@ -159,11 +160,10 @@ message SignedPriceOfAssetPair { } ``` -This message is expected to fail if: - -* the Relayer (`sender`) is not an authorized oracle publisher or if `assetId` is not unique amongst the provided asset pairs -* ECDSA signature verification fails for the `SignedPriceOfAssetPair` -* the difference between timestamps exceeds the `MaxStorkTimestampIntervalNano` (500 milliseconds). +This message is expected to fail if: +- the Relayer (`sender`) is not an authorized oracle publisher or if `assetId` is not unique amongst the provided asset pairs +- ECDSA signature verification fails for the `SignedPriceOfAssetPair` +- the difference between timestamps exceeds the `MaxStorkTimestampIntervalNano` (500 milliseconds). ## MsgRelayProviderPrices diff --git a/.gitbook/developers-native/injective/oracle/04_proposals.mdx b/.gitbook/developers-native/injective/oracle/04_proposals.md similarity index 96% rename from .gitbook/developers-native/injective/oracle/04_proposals.mdx rename to .gitbook/developers-native/injective/oracle/04_proposals.md index 9b6a609..dc921b3 100644 --- a/.gitbook/developers-native/injective/oracle/04_proposals.mdx +++ b/.gitbook/developers-native/injective/oracle/04_proposals.md @@ -3,7 +3,7 @@ sidebar_position: 4 title: Governance Proposals --- -# Proposals +# Governance Proposals ## GrantBandOraclePrivilegeProposal @@ -90,8 +90,8 @@ message AuthorizeBandOracleRequestProposal { ## UpdateBandOracleRequestProposal -This proposal is used for deleting a request or updating the request.\ -When `DeleteRequestId` is not zero, it deletes the request with the id and finish its execution.\ +This proposal is used for deleting a request or updating the request. +When `DeleteRequestId` is not zero, it deletes the request with the id and finish its execution. When `DeleteRequestId` is zero, it update the request with id `UpdateOracleRequest.RequestId` to UpdateOracleRequest. ```protobuf @@ -108,7 +108,7 @@ message UpdateBandOracleRequestProposal { ## EnableBandIBCProposal -This proposal is to enable IBC connection between Band chain and Injective chain.\ +This proposal is to enable IBC connection between Band chain and Injective chain. When the proposal is approved, it updates the BandIBCParams into newer one configured on the proposal. ```protobuf @@ -123,7 +123,7 @@ message EnableBandIBCProposal { } ``` -The details of `BandIBCParams`, can be checked at [**State**](01_state.md) +The details of `BandIBCParams`, can be checked at **[State](./01_state.md)** ## GrantStorkPublisherPrivilegeProposal @@ -163,4 +163,4 @@ message RevokeStorkPublisherPrivilegeProposal { repeated string stork_publishers = 3; } -``` +``` \ No newline at end of file diff --git a/.gitbook/developers-native/injective/oracle/05_events.mdx b/.gitbook/developers-native/injective/oracle/05_events.md similarity index 100% rename from .gitbook/developers-native/injective/oracle/05_events.mdx rename to .gitbook/developers-native/injective/oracle/05_events.md diff --git a/.gitbook/developers-native/injective/oracle/06_future_improvements.mdx b/.gitbook/developers-native/injective/oracle/06_future_improvements.md similarity index 100% rename from .gitbook/developers-native/injective/oracle/06_future_improvements.mdx rename to .gitbook/developers-native/injective/oracle/06_future_improvements.md diff --git a/.gitbook/developers-native/injective/oracle/99_errors.mdx b/.gitbook/developers-native/injective/oracle/99_errors.md similarity index 100% rename from .gitbook/developers-native/injective/oracle/99_errors.mdx rename to .gitbook/developers-native/injective/oracle/99_errors.md diff --git a/.gitbook/developers-native/injective/oracle.mdx b/.gitbook/developers-native/injective/oracle/index.md similarity index 100% rename from .gitbook/developers-native/injective/oracle.mdx rename to .gitbook/developers-native/injective/oracle/index.md diff --git a/.gitbook/developers-native/injective/peggy.mdx b/.gitbook/developers-native/injective/peggy.mdx deleted file mode 100644 index 1b845f4..0000000 --- a/.gitbook/developers-native/injective/peggy.mdx +++ /dev/null @@ -1,39 +0,0 @@ -# Peggy - -## Abstract - -The peggy module enables the Injective Chain to support a trustless, on-chain bidirectional ERC-20 token bridge to Ethereum. In this system,\ -holders of ERC-20 tokens on Ethereum can convert their ERC-20 tokens to Cosmos-native coins on\ -the Injective Chain and vice-versa. - -This decentralized bridge is secured and operated by the validators of the Injective Chain. - -## Contents - -1. [Definitions](01_definitions.md) -2. [Workflow](02_workflow.md) -3. [State](03_state.md) -4. [Messages](04_messages.md) -5. [Slashing](05_slashing.md) -6. [End-Block](06_end_block.md) -7. [Events](07_events.md) -8. [Parameters](08_params.md) - -### Components - -1. [**Peggy**](https://etherscan.io/address/0xF955C57f9EA9Dc8781965FEaE0b6A2acE2BAD6f3) **smart contract on Ethereum** -2. **Peggy module on the Injective Chain** -3. [**Peggo**](https://github.com/InjectiveLabs/peggo) **(off-chain relayer aka orchestrator)** - * **Oracle** (Observes events of Peggy contract and send claims to the Peggy module) - * **EthSigner** (Signs Valset and Batch confirmations to the Peggy module) - * **Batch Requester** (Sends batch token withdrawal requests to the Peggy module) - * **Valset Relayer** (Submits Validator set updates to the Peggy contract) - * **Batch Relayer** (Submits batches of token withdrawals to the Peggy contract) - -In addition to running an `injectived` node to sign blocks, Injective Chain validators must also run the `peggo` orchestrator to relay data from the Peggy smart contract on Ethereum and the Peggy module on the Injective Chain. - -### Peggo Functionalities - -1. **Maintaining an up-to-date checkpoint of the Injective Chain validator set on Ethereum** -2. **Transferring ERC-20 tokens from Ethereum to the Injective Chain** -3. **Transferring pegged tokens from the Injective Chain to Ethereum** diff --git a/.gitbook/developers-native/injective/peggy/01_definitions.mdx b/.gitbook/developers-native/injective/peggy/01_definitions.md similarity index 62% rename from .gitbook/developers-native/injective/peggy/01_definitions.mdx rename to .gitbook/developers-native/injective/peggy/01_definitions.md index 9fb2dc0..037c1da 100644 --- a/.gitbook/developers-native/injective/peggy/01_definitions.mdx +++ b/.gitbook/developers-native/injective/peggy/01_definitions.md @@ -3,32 +3,34 @@ sidebar_position: 1 title: Definitions --- -# Definitions +# Intro -This doc aims to provide an overview of `Peggy` (Injective's Ethereum bridge) from a technical perspective and dive deep into its operational logic.\ -Peggy is the name of the custom Cosmos SDK module built on Injective as well as the Ethereum contract (Peggy.sol) which make up both sides of the bridge.\ -Connected via a middle-man process called `Peggo` users can securely move token assets between networks. +This doc aims to provide an overview of `Peggy` (Injective's Ethereum bridge) from a technical perspective and dive deep into its operational logic. +Peggy is the name of the custom Cosmos SDK module built on Injective as well as the Ethereum contract (Peggy.sol) which make up both sides of the bridge. +Connected via a middle-man process called `Peggo` users can securely move token assets between networks. To suggest improvements, please open a GitHub issue. ### Key definitions -Words matter and we seek clarity in the terminology so we can have clarity in our thinking and communication.\ +Words matter and we seek clarity in the terminology so we can have clarity in our thinking and communication. To help better understand, some key definitions are: -* `Operator` - this is a person (or people) who control and operate `Validator` and `Orchestrator` processes -* `Validator` - this is an Injective Chain validating node (eg. `injectived` process) -* `Validator Set` - the (active) set of Injective Chain `Validators` (Valset) along with their respective voting power as determined by their stake weight. Each validator is associated with an Ethereum address to be represented on the Ethereum network -* `Orchestrator (Peggo)` - the off-chain process (`peggo`) that plays the middleman role between Injective and Ethereum. Orchestrators are responsible for keeping the bridge online and require active endpoints to fully synced Injective (Ethereum) nodes -* `Peggy module` - the counterparty Cosmos module for `Peggy contract`. Besides providing services to bridge token assets, it automatically reflects on the active `Validator Set` as it changes over time. The update is later applied on Ethereum via `Peggo` -* `Peggy Contract` - The Ethereum contract that holds all the ERC-20 tokens. It also maintains a compressed checkpointed representation of the Injective Chain `Validator Set` using `Delegate Keys` and normalized powers -* `Delegate Keys` - when an `Operator` sets up their `Orchestrator` for the first time they register (on Injective) their `Validator`'s address with an Ethereum address. The corresponding key is used to sign messages and represent that validator on Ethereum.\ +- `Operator` - this is a person (or people) who control and operate `Validator` and `Orchestrator` processes +- `Validator` - this is an Injective Chain validating node (eg. `injectived` process) +- `Validator Set` - the (active) set of Injective Chain `Validators` (Valset) along with their respective voting power as determined by their stake weight. Each validator is associated with an Ethereum address to be represented on the Ethereum network +- `Orchestrator (Peggo)` - the off-chain process (`peggo`) that plays the middleman role between Injective and Ethereum. Orchestrators are responsible for keeping the bridge online and require active endpoints to fully synced Injective (Ethereum) nodes +- `Peggy module` - the counterparty Cosmos module for `Peggy contract`. Besides providing services to bridge token assets, it automatically reflects on the active `Validator Set` as it changes over time. The update is later applied on Ethereum via `Peggo` +- `Peggy Contract` - The Ethereum contract that holds all the ERC-20 tokens. It also maintains a compressed checkpointed representation of the Injective Chain `Validator Set` using `Delegate Keys` and normalized powers +- `Delegate Keys` - when an `Operator` sets up their `Orchestrator` for the first time they register (on Injective) their `Validator`'s address with an Ethereum address. The corresponding key is used to sign messages and represent that validator on Ethereum. Optionally, one delegate Injective Chain account key can be provided to sign Injective messages (eg `Claims`) on behalf of the `Validator` -* `Peggy Tx pool (withdrawals)` - when a user wishes to move their asset from Injective to Ethereum their individual tx gets pooled with others with the same asset -* `Peggy Batch pool` - pooled withdrawals are batched together (by an `Orchestrator`) to be signed off and eventually relayed to Ethereum. These batches are kept within this pool -* `Claim` - a signed proof (by an `Orchestrator`) that an event occurred in the `Peggy contract` -* `Attestation` - an aggregate of claims for a particular event nonce emitted from `Peggy contract`. After a majority of `Orchestrators` attests to a claim, the event is acknowledged and executed on Injective -* `Majority` - the majority of Injective network, 2/3 + 1 validators -* `Deposit` - an asset transfer initiated from Ethereum to Injective -* `Withdrawal` - an asset transfer initiated from Injective to Ethereum (present in `Peggy Tx pool`) -* `Batch` - a batch of withdrawals with the same token type (present in `Peggy Batch pool`) +- `Peggy Tx pool (withdrawals)` - when a user wishes to move their asset from Injective to Ethereum their individual tx gets pooled with others with the same asset +- `Peggy Batch pool` - pooled withdrawals are batched together (by an `Orchestrator`) to be signed off and eventually relayed to Ethereum. These batches are kept within this pool +- `Claim` - a signed proof (by an `Orchestrator`) that an event occurred in the `Peggy contract` +- `Attestation` - an aggregate of claims for a particular event nonce emitted from `Peggy contract`. After a majority of `Orchestrators` attests to a claim, the event is acknowledged and executed on Injective +- `Majority` - the majority of Injective network, 2/3 + 1 validators +- `Deposit` - an asset transfer initiated from Ethereum to Injective +- `Withdrawal` - an asset transfer initiated from Injective to Ethereum (present in `Peggy Tx pool`) +- `Batch` - a batch of withdrawals with the same token type (present in `Peggy Batch pool`) + + diff --git a/.gitbook/developers-native/injective/peggy/02_workflow.mdx b/.gitbook/developers-native/injective/peggy/02_workflow.md similarity index 69% rename from .gitbook/developers-native/injective/peggy/02_workflow.mdx rename to .gitbook/developers-native/injective/peggy/02_workflow.md index b091282..2a7b474 100644 --- a/.gitbook/developers-native/injective/peggy/02_workflow.mdx +++ b/.gitbook/developers-native/injective/peggy/02_workflow.md @@ -13,14 +13,12 @@ To recap, each `Operator` is responsible for maintaining 2 secure processes: 2. The `Orchestrator` service (`peggo orchestrator` process) which interacts with both networks. Implicitly, an RPC endpoint to a fully synced Ethereum node is required as well (see peggo .env example) Combined, these 2 entities accomplish 3 things: +- Move token assets from Ethereum to Injective +- Move token assets from Injective to Ethereum +- Keep the `Peggy.sol` contract in sync with the active `Validator Set` on Injective -* Move token assets from Ethereum to Injective -* Move token assets from Injective to Ethereum -* Keep the `Peggy.sol` contract in sync with the active `Validator Set` on Injective - -It is possible to run `peggo` without ever being a `Validator`. Peggo automatically runs in "relayer mode" when configured to run with an address **not associated** with a `Validator`.\ +It is possible to run `peggo` without ever being a `Validator`. Peggo automatically runs in "relayer mode" when configured to run with an address **not associated** with a `Validator`. In this mode, only 2 things can happen: - * new token batches can be created on Injective * confirmed valsets/batches can be relayed to Ethereum @@ -36,7 +34,7 @@ These representative tokens have a denomination prefix of `peggy` concatenated w ### Native Cosmos SDK assets -An asset native to a Cosmos SDK chain (e.g. `ATOM`) first must be represented on Ethereum before it's possible to bridge it. To do so, the [Peggy contract](https://github.com/InjectiveLabs/peggo/blob/master/solidity/contracts/Peggy.sol) allows anyone to create a new ERC-20 token representing a Cosmos asset by calling the `deployERC20` function. +An asset native to a Cosmos SDK chain (e.g. `ATOM`) first must be represented on Ethereum before it's possible to bridge it. To do so, the [Peggy contract](https://github.com/InjectiveLabs/peggo/blob/master/solidity/contracts/Peggy.sol) allows anyone to create a new ERC-20 token representing a Cosmos asset by calling the `deployERC20` function. This endpoint is not permissioned, so it is up to the validators and the users of the Peggy bridge to declare any given ERC-20 token as the representation of a given asset. @@ -46,41 +44,41 @@ The peggo orchestrators observe this event and decide if a Cosmos asset has been ## `Orchestrator` (Peggo) subprocesses -The `peggo orchestrator` process consists of 4 subprocesses running concurrently at exact intervals (loops). These are: - -* `Signer` which signs new `Validator Set` updates and `Token Batches` with the `Operator`'s Ethereum keys and submits using [messages](04_messages.md#Ethereum-Signer-messages). -* `Oracle` which observes Ethereum events and sends them as [claims](04_messages.md#Oracle-messages) to Injective. +The `peggo orchestrator` process consists of 4 subprocesses running concurrently at exact intervals (loops). These are: +* `Signer` which signs new `Validator Set` updates and `Token Batches` with the `Operator`'s Ethereum keys and submits using [messages](./04_messages.md#Ethereum-Signer-messages). +* `Oracle` which observes Ethereum events and sends them as [claims](./04_messages.md#Oracle-messages) to Injective. * `Relayer` which submits confirmed `Validator Set` updates and `Token Batches` to the `Peggy Contract` on Ethereum * `Batch Creator` which observes (new) withdrawals on Injective and decides which of these to batch according to their type and the configured `PEGGO_MIN_BATCH_FEE_USD` value ### Batch Creator -The purpose of the `Batch Creator` is only in creating token batches on the Injective side. The relevant `Peggy module` RPC is not permissioned so anyone can create a batch. +The purpose of the `Batch Creator` is only in creating token batches on the Injective side. The relevant `Peggy module` RPC is not permissioned so anyone can create a batch. -When a user wants to withdraw assets from Injective to Ethereum they send a special message to Injective (`MsgSendToEth`) which adds their withdrawal to `Peggy Tx Pool`.`Batch Creator` continually queries the pool for withdrawals (by token type) and issues a `MsgRequestBatch` to Injective when a potential batch satisfies the configured `PEGGO_MIN_BATCH_FEE_USD` value (see .env example). +When a user wants to withdraw assets from Injective to Ethereum they send a special message to Injective (`MsgSendToEth`) which adds their withdrawal to `Peggy Tx Pool`. +`Batch Creator` continually queries the pool for withdrawals (by token type) and issues a `MsgRequestBatch` to Injective when a potential batch satisfies the configured `PEGGO_MIN_BATCH_FEE_USD` value (see .env example). On the receiving end, all pooled withdrawals matching the token type in the request are moved from the `Outgoing Tx Pool` as a single batch and placed in the `Outgoing Batch Pool`. ### Signer -The responsibility of Signer is to provide confirmations that an `Operator (Orchestrator)` is partaking in bridge activity. Failure to provide these confirmations results in slashing penalties for the orchestrator's `Validator`.\ +The responsibility of Signer is to provide confirmations that an `Operator (Orchestrator)` is partaking in bridge activity. Failure to provide these confirmations results in slashing penalties for the orchestrator's `Validator`. In other words, this process **must be running at all times** for a `Validator` node. -Any payload moving in the Injective->Ethereum pipeline (`Validator Set` updates/`Token Batches`) requires `Validator` signatures to be successfully relayed to Ethereum. Certain calls on `Peggy Contract` accept an array of signatures to be checked against the `Validator Set` in the contract itself.`Orchestrators` make these signatures with their `Delegate Ethereum address`: this is an Ethereum address decided by the `Operator` upon initial setup ([SetOrchestratorAddress](04_messages.md#setorchestratoraddresses)). This address then represents that validator on the Ethereum blockchain and will be added as a signing member of the multisig with a weighted voting power as close as possible to the Injective Chain voting power. +Any payload moving in the Injective->Ethereum pipeline (`Validator Set` updates/`Token Batches`) requires `Validator` signatures to be successfully relayed to Ethereum. Certain calls on `Peggy Contract` accept an array of signatures to be checked against the `Validator Set` in the contract itself. +`Orchestrators` make these signatures with their `Delegate Ethereum address`: this is an Ethereum address decided by the `Operator` upon initial setup ([SetOrchestratorAddress](./04_messages.md#setorchestratoraddresses)). This address then represents that validator on the Ethereum blockchain and will be added as a signing member of the multisig with a weighted voting power as close as possible to the Injective Chain voting power. Whenever `Signer` finds that there is a unconfirmed valset update (token batch) present within the `Peggy Module` it issues a `MsgConfirmValset` (`MsgConfirmBatch`) as proof that the operating `Validator` is active in bridge activity. ### Oracle -Monitors the Ethereum network for new events involving the `Peggy Contract`. +Monitors the Ethereum network for new events involving the `Peggy Contract`. -Every event emitted by the contract has a unique event nonce. This nonce value is crucial in coordinating `Orchestrators` to properly observe contract activity and make sure Injective acknowledges them via `Claims`.\ +Every event emitted by the contract has a unique event nonce. This nonce value is crucial in coordinating `Orchestrators` to properly observe contract activity and make sure Injective acknowledges them via `Claims`. Multiple claims of the same nonce make up an `Attestation` and when the majority (2/3) of orchestrators have observed an event its particular logic gets executed on Injective. -If 2/3 of the validators can not agree on a single `Attestation`, the oracle is halted. This means no new events will be relayed from Ethereum until some of the validators change their votes. There is no slashing condition for this, with reasoning outlined in the [slashing spec](05_slashing.md) +If 2/3 of the validators can not agree on a single `Attestation`, the oracle is halted. This means no new events will be relayed from Ethereum until some of the validators change their votes. There is no slashing condition for this, with reasoning outlined in the [slashing spec](./05_slashing.md) There are 4 types of events emitted from Peggy.sol: - 1. `TransactionBatchExecutedEvent` - event indicating that a token batch (withdrawals) has been successfully relayed to Ethereum 2. `ValsetUpdatedEvent` - event indicating that a `Validator Set` update has been successfully relayed to Ethereum 3. `SendToInjectiveEvent` - event indicating that a new deposit to Injective has been initiated @@ -92,77 +90,75 @@ Injective's `Oracle` implementation ignores the last 12 blocks on Ethereum to en `Relayer` bundles valset updates (or token batches) along with their confirmations into an Ethereum transaction and sends it to the `Peggy contract`. -Keep in mind that these messages cost a variable amount of money based on wildly changing Ethereum gas prices, so it's not unreasonable for a single batch to cost over a million gas.\ +Keep in mind that these messages cost a variable amount of money based on wildly changing Ethereum gas prices, so it's not unreasonable for a single batch to cost over a million gas. A major design decision for our relayer rewards was to always issue them on the Ethereum chain. This has downsides, namely some strange behavior in the case of validator set update rewards. But the upsides are undeniable, because the Ethereum messages pay `msg.sender` any existing bot in the Ethereum ecosystem will pick them up and try to submit them. This makes the relaying market much more competitive and less prone to cabal like behavior. -## End-to-end Lifecycle +## End-to-end Lifecycle -This document describes the end to end lifecycle of the Peggy bridge. +This document describes the end to end lifecycle of the Peggy bridge. ### Peggy Smart Contract Deployment -In order to deploy the Peggy contract, the validator set of the native chain (Injective Chain) must be known. Upon deploying the Peggy contract suite (Peggy Implementation, Proxy contract, and ProxyAdmin contracts), the Peggy contract (the Proxy contract) must be initialized with the validator set.\ +In order to deploy the Peggy contract, the validator set of the native chain (Injective Chain) must be known. Upon deploying the Peggy contract suite (Peggy Implementation, Proxy contract, and ProxyAdmin contracts), the Peggy contract (the Proxy contract) must be initialized with the validator set. Upon initialization a `ValsetUpdatedEvent` is emitted from the contract. -The proxy contract is used to upgrade Peggy Implementation contract which is needed for bug fixing and potential improvements during initial phase. It is a simple wrapper or "proxy" which users interact with directly and is in charge of forwarding transactions to the Peggy implementation contract, which contains the logic. The key concept to understand is that the implementation contract can be replaced but the proxy (the access point) is never changed. +The proxy contract is used to upgrade Peggy Implementation contract which is needed for bug fixing and potential improvements during initial phase. It is a simple wrapper or "proxy" which users interact with directly and is in charge of forwarding transactions to the Peggy implementation contract, which contains the logic. The key concept to understand is that the implementation contract can be replaced but the proxy (the access point) is never changed. -The ProxyAdmin is a central admin for the Peggy proxy, which simplifies management. It controls upgradability and ownership transfers. The ProxyAdmin contract itself has a built-in expiration time which, once expired, prevents the Peggy implementation contract from being upgraded in the future. +The ProxyAdmin is a central admin for the Peggy proxy, which simplifies management. It controls upgradability and ownership transfers. The ProxyAdmin contract itself has a built-in expiration time which, once expired, prevents the Peggy implementation contract from being upgraded in the future. Then the following peggy genesis params should be updated: - -1. `bridge_ethereum_address` with Peggy proxy contract address +1. `bridge_ethereum_address` with Peggy proxy contract address 2. `bridge_contract_start_height` with the height at which the Peggy proxy contract was deployed -This completes the bootstrap of the Peggy bridge and the chain can be started. Afterward, `Operators` should start their `peggo` processes and eventually observe that the initial `ValsetUpdatedEvent` is attested on Injective. +This completes the bootstrap of the Peggy bridge and the chain can be started. Afterward, `Operators` should start their `peggo` processes and eventually observe that the initial `ValsetUpdatedEvent` is attested on Injective. ### **Updating Injective Chain validator set on Ethereum** -![img.png](../../../developers/modules/injective/peggy/images/valsetupdate.png) - -A validator set is a series of Ethereum addresses with attached normalized powers used to represent the Injective validator set (Valset) in the Peggy contract on Ethereum. The Peggy contract stays in sync with the Injective Chain validator set through the following mechanism: +![img.png](./images/valsetupdate.png) +A validator set is a series of Ethereum addresses with attached normalized powers used to represent the Injective validator set (Valset) in the Peggy contract on Ethereum. The Peggy contract stays in sync with the Injective Chain validator set through the following mechanism: 1. **Creating a new Valset on Injective:** A new Valset is automatically created on the Injective Chain when either: * the cumulative difference of the current validator set powers compared to the last recorded Valset exceeds 5% * a validator begins unbonding from the set 2. **Confirming a Valset on Injective:** Each `Operator` is responsible for confirming Valset updates that are created on Injective. The `Signer` process sends these confirmations via `MsgConfirmValset` by having the validator's delegated Ethereum key sign over a compressed representation of the Valset data. The `Peggy module` verifies the validity of the signature and persists it to its state. -3. **Updating the Valset on the Peggy contract:** After a 2/3+ 1 majority of validators have submitted their confirmations for a given Valset, `Relayer` submits the new Valset data to the Peggy contract by calling `updateValset`.\ - The Peggy contract then validates the data, updates the valset checkpoint, transfers valset rewards to sender and emits a `ValsetUpdatedEvent`. -4. **Acknowledging the `ValsetUpdatedEvent` on Injective:** `Oracle` witnesses the `ValsetUpdatedEvent` on Ethereum, and sends a `MsgValsetUpdatedClaim` which informs the `Peggy module` that the Valset has been updated on Ethereum. -5. **Pruning Valsets on Injective:** Once a 2/3 majority of validators send their claim for a given `ValsetUpdateEvent`, all the previous valsets are pruned from the `Peggy module` state. -6. **Validator Slashing:** Validators are subject to slashing after a configured window of time (`SignedValsetsWindow`) for not providing confirmations. Read more [valset slashing](05_slashing.md) +3. **Updating the Valset on the Peggy contract:** After a 2/3+ 1 majority of validators have submitted their confirmations for a given Valset, `Relayer` submits the new Valset data to the Peggy contract by calling `updateValset`. +The Peggy contract then validates the data, updates the valset checkpoint, transfers valset rewards to sender and emits a `ValsetUpdatedEvent`. +4. **Acknowledging the `ValsetUpdatedEvent` on Injective:** `Oracle` witnesses the `ValsetUpdatedEvent` on Ethereum, and sends a `MsgValsetUpdatedClaim` which informs the `Peggy module` that the Valset has been updated on Ethereum. +5. **Pruning Valsets on Injective:** Once a 2/3 majority of validators send their claim for a given `ValsetUpdateEvent`, all the previous valsets are pruned from the `Peggy module` state. +6. **Validator Slashing:** Validators are subject to slashing after a configured window of time (`SignedValsetsWindow`) for not providing confirmations. Read more [valset slashing](./05_slashing.md) -*** +---- ### **Transferring ERC-20 tokens from Ethereum to Injective** -![img.png](../../../developers/modules/injective/peggy/images/SendToCosmos.png) +![img.png](./images/SendToCosmos.png) ERC-20 tokens are transferred from Ethereum to Injective through the following mechanism: + 1. **Depositing ERC-20 tokens on the Peggy Contract:** A user initiates a transfer of ERC-20 tokens from Ethereum to Injective by calling the `sendToInjective` function on the Peggy contract which deposits tokens on the Peggy contract and emits a `SendToInjectiveEvent`. + The deposited tokens will remain locked until withdrawn at some undetermined point in the future. This event contains the amount and type of tokens, as well as a destination address on the Injective Chain to receive the funds. -1. **Depositing ERC-20 tokens on the Peggy Contract:** A user initiates a transfer of ERC-20 tokens from Ethereum to Injective by calling the `sendToInjective` function on the Peggy contract which deposits tokens on the Peggy contract and emits a `SendToInjectiveEvent`.\ - The deposited tokens will remain locked until withdrawn at some undetermined point in the future. This event contains the amount and type of tokens, as well as a destination address on the Injective Chain to receive the funds. -2. **Confirming the deposit:** Each `Oracle` witnesses the `SendToInjectiveEvent` and sends a `MsgDepositClaim` which contains the deposit information to the Peggy module. -3. **Minting tokens on the Injective:** Once a majority of validators confirm the deposit claim, the deposit is processed. + 2. **Confirming the deposit:** Each `Oracle` witnesses the `SendToInjectiveEvent` and sends a `MsgDepositClaim` which contains the deposit information to the Peggy module. -* If the asset is Ethereum originated, the tokens are minted and transferred to the intended recipient's address on the Injective Chain. -* If the asset is Cosmos-SDK originated, the coins are unlocked and transferred to the intended recipient's address on the Injective Chain. - -*** + 3. **Minting tokens on the Injective:** Once a majority of validators confirm the deposit claim, the deposit is processed. + - If the asset is Ethereum originated, the tokens are minted and transferred to the intended recipient's address on the Injective Chain. + - If the asset is Cosmos-SDK originated, the coins are unlocked and transferred to the intended recipient's address on the Injective Chain. +----- ### **Withdrawing tokens from Injective to Ethereum** -![img.png](../../../developers/modules/injective/peggy/images/SendToEth.png) +![img.png](./images/SendToEth.png) 1. **Request Withdrawal from Injective:** A user can initiate the transfer of assets from the Injective Chain to Ethereum by sending a `MsgSendToEth` transaction to the peggy module. - * If the asset is Ethereum native, the represented tokens are burnt. - * If the asset is Cosmos SDK native, coins are locked in the module. The withdrawal is then added to `Outgoing Tx Pool`. + * If the asset is Ethereum native, the represented tokens are burnt. + * If the asset is Cosmos SDK native, coins are locked in the module. The withdrawal is then added to `Outgoing Tx Pool`. 2. **Batch Creation:** A `Batch Creator` observes the pool of pending withdrawals. The batch creator (or any external third party) then requests a batch of to be created for given token by sending `MsgRequestBatch` to the Injective Chain. The `Peggy module` collects withdrawals matching the token type into a batch and puts it in `Outgoing Batch Pool`. -3. **Batch Confirmation:** Upon detecting the existence of an Outgoing Batch, the `Signer` signs over the batch with its Ethereum key and submits a `MsgConfirmBatch` tx to the Peggy module. -4. **Submit Batch to Peggy Contract:** Once a majority of validators confirm the batch, the `Relayer` calls `submitBatch` on the Peggy contract with the batch and its confirmations. The Peggy contract validates the signatures, updates the batch checkpoint, processes the batch ERC-20 withdrawals, transfers the batch fee to the tx sender and emits a `TransactionBatchExecutedEvent`. +3. **Batch Confirmation:** Upon detecting the existence of an Outgoing Batch, the `Signer` signs over the batch with its Ethereum key and submits a `MsgConfirmBatch` tx to the Peggy module. +4. **Submit Batch to Peggy Contract:** Once a majority of validators confirm the batch, the `Relayer` calls `submitBatch` on the Peggy contract with the batch and its confirmations. The Peggy contract validates the signatures, updates the batch checkpoint, processes the batch ERC-20 withdrawals, transfers the batch fee to the tx sender and emits a `TransactionBatchExecutedEvent`. 5. **Send Withdrawal Claim to Injective:** `Oracles` witness the `TransactionBatchExecutedEvent` and send a `MsgWithdrawClaim` containing the withdrawal information to the Peggy module. -6. **Prune Batches** Once a majority of validators submit their `MsgWithdrawClaim` , the batch is deleted along and all previous batches are cancelled on the Peggy module. Withdrawals in cancelled batches get moved back into `Outgoing Tx Pool`. -7. **Batch Slashing:** Validators are responsible for confirming batches and are subject to slashing if they fail to do so. Read more on [batch slashing](05_slashing.md). +6. **Prune Batches** Once a majority of validators submit their `MsgWithdrawClaim` , the batch is deleted along and all previous batches are cancelled on the Peggy module. Withdrawals in cancelled batches get moved back into `Outgoing Tx Pool`. +7. **Batch Slashing:** Validators are responsible for confirming batches and are subject to slashing if they fail to do so. Read more on [batch slashing](./05_slashing.md). Note while that batching reduces individual withdrawal costs dramatically, this comes at the cost of latency and implementation complexity. If a user wishes to withdraw quickly they will have to pay a much higher fee. However this fee will be about the same as the fee every withdrawal from the bridge would require in a non-batching system. + diff --git a/.gitbook/developers-native/injective/peggy/03_state.mdx b/.gitbook/developers-native/injective/peggy/03_state.md similarity index 77% rename from .gitbook/developers-native/injective/peggy/03_state.mdx rename to .gitbook/developers-native/injective/peggy/03_state.md index 7e45797..da3b165 100644 --- a/.gitbook/developers-native/injective/peggy/03_state.mdx +++ b/.gitbook/developers-native/injective/peggy/03_state.md @@ -9,20 +9,21 @@ This doc lists all the data Peggy module reads/writes to its state as KV pairs ### Module Params -Params is a module-wide configuration structure that stores parameters and defines overall functioning of the peggy module. Detailed specification for each parameter can be found in the [Parameters section](08_params.md). +Params is a module-wide configuration structure that stores parameters and defines overall functioning of the peggy module. Detailed specification for each parameter can be found in the [Parameters section](./08_params.md). | key | Value | Type | Encoding | -| ------------- | ------------- | -------------- | ---------------- | +|---------------|---------------|----------------|------------------| | `[]byte{0x4}` | Module params | `types.Params` | Protobuf encoded | + ### Validator Info -#### Ethereum Address by Validator +#### Ethereum Address by Validator -Stores `Delegate Ethereum address` indexed by the `Validator`'s account address +Stores `Delegate Ethereum address` indexed by the `Validator`'s account address | key | Value | Type | Encoding | -| ------------------------------------- | ---------------- | ---------------- | ---------------- | +|---------------------------------------|------------------|------------------|------------------| | `[]byte{0x1} + []byte(validatorAddr)` | Ethereum address | `common.Address` | Protobuf encoded | #### Validator by Ethereum Address @@ -30,17 +31,19 @@ Stores `Delegate Ethereum address` indexed by the `Validator`'s account address Stores `Validator` account address indexed by the `Delegate Ethereum address` | key | Value | Type | Encoding | -| ----------------------------------- | ----------------- | ---------------- | ---------------- | +|-------------------------------------|-------------------|------------------|------------------| | `[]byte{0xfb} + []byte(ethAddress)` | Validator address | `sdk.ValAddress` | Protobuf encoded | + #### OrchestratorValidator When a validator would like to delegate their voting power to another key. The value is stored using the orchestrator address as the key | Key | Value | Type | Encoding | -| ----------------------------------- | -------------------------------------------- | -------- | ---------------- | +|-------------------------------------|----------------------------------------------|----------|------------------| | `[]byte{0xe8} + []byte(AccAddress)` | Orchestrator address assigned by a validator | `[]byte` | Protobuf encoded | + ### Valset This is the validator set of the bridge. Created automatically by `Peggy module` during EndBlocker. @@ -59,7 +62,7 @@ type Valset struct { ``` | key | Value | Type | Encoding | -| ------------------------------------------ | ------------- | -------------- | ---------------- | +|--------------------------------------------|---------------|----------------|------------------| | `[]byte{0x2} + nonce (big endian encoded)` | Validator set | `types.Valset` | Protobuf encoded | ### SlashedValsetNonce @@ -67,33 +70,35 @@ type Valset struct { The latest validator set slash nonce. This is used to track which validator set needs to be slashed and which already has been. | Key | Value | Type | Encoding | -| -------------- | ----- | ------ | ---------------------- | +|----------------|-------|--------|------------------------| | `[]byte{0xf5}` | Nonce | uint64 | encoded via big endian | ### ValsetNonce -Nonce of the latest validator set. Updated on each new validator set. +Nonce of the latest validator set. Updated on each new validator set. | key | Value | Type | Encoding | -| -------------- | ----- | -------- | ---------------------- | +|----------------|-------|----------|------------------------| | `[]byte{0xf6}` | Nonce | `uint64` | encoded via big endian | + ### Valset Confirmation -`Singer` confirmation for a particular validator set. See [oracle messages](04_messages.md#ValsetConfirm) +`Singer` confirmation for a particular validator set. See [oracle messages](./04_messages.md#ValsetConfirm) | Key | Value | Type | Encoding | -| ------------------------------------------- | ---------------------- | ------------------------ | ---------------- | +|---------------------------------------------|------------------------|--------------------------|------------------| | `[]byte{0x3} + (nonce + []byte(AccAddress)` | Validator Confirmation | `types.MsgValsetConfirm` | Protobuf encoded | ### Batch Confirmation -`Singer` confirmation for a particular token batch. See [oracle messages](04_messages.md#ConfirmBatch) +`Singer` confirmation for a particular token batch. See [oracle messages](./04_messages.md#ConfirmBatch) | Key | Value | Type | Encoding | -| ------------------------------------------------------------------- | ---------------------------- | ----------------------- | ---------------- | +|---------------------------------------------------------------------|------------------------------|-------------------------|------------------| | `[]byte{0xe1} + []byte(tokenContract) + nonce + []byte(AccAddress)` | Validator Batch Confirmation | `types.MsgConfirmBatch` | Protobuf encoded | + ### OutgoingTransferTx User withdrawals are pooled together in `Peggy Tx Pool` ready to be batched later by a `Batch Creator`. @@ -111,22 +116,24 @@ type OutgoingTransferTx struct { ``` | Key | Value | Type | Encoding | -| -------------------------------------- | ---------------------------- | -------- | ------------------ | +|----------------------------------------|------------------------------|----------|--------------------| | `[]byte{0x7} + []byte("lastTxPoolId")` | nonce of outgoing withdrawal | `uint64` | Big endian encoded | + ### LastTXPoolID Monotonically increasing value for each withdrawal received by Injective | Key | Value | Type | Encoding | -| -------------------------------------- | ----------------------- | -------- | ------------------ | +|----------------------------------------|-------------------------|----------|--------------------| | `[]byte{0x6} + []byte("lastTxPoolId")` | Last used withdrawal ID | `uint64` | Big endian encoded | + ### OutgoingTxBatch `OutgoingTxBatch` represents a collection of withdrawals of the same token type. Created on every successful `MsgRequestBatch`. -Stored in two possible ways, first with a height and second without (unsafe). Unsafe is used for testing and export and import of state.\ +Stored in two possible ways, first with a height and second without (unsafe). Unsafe is used for testing and export and import of state. Currently [Peggy.sol](https://github.com/InjectiveLabs/peggo/blob/master/solidity/contracts/Peggy.sol) is hardcoded to only accept batches with a single token type and only pay rewards in that same token type. ```go @@ -140,24 +147,25 @@ type OutgoingTxBatch struct { ``` | key | Value | Type | Encoding | -| ------------------------------------------------------------------ | -------------------------------- | ----------------------- | ---------------- | +|--------------------------------------------------------------------|----------------------------------|-------------------------|------------------| | `[]byte{0xa} + []byte(tokenContract) + nonce (big endian encoded)` | A batch of outgoing transactions | `types.OutgoingTxBatch` | Protobuf encoded | | `[]byte{0xb} + block (big endian encoded)` | A batch of outgoing transactions | `types.OutgoingTxBatch` | Protobuf encoded | + ### LastOutgoingBatchID Monotonically increasing value for each batch created on Injective by some `Batch Creator` | Key | Value | Type | Encoding | -| ------------------------------------- | ------------------ | -------- | ------------------ | +|---------------------------------------|--------------------|----------|--------------------| | `[]byte{0x7} + []byte("lastBatchId")` | Last used batch ID | `uint64` | Big endian encoded | ### SlashedBlockHeight -Represents the latest slashed block height. There is always only a singe value stored. +Represents the latest slashed block height. There is always only a singe value stored. | Key | Value | Type | Encoding | -| -------------- | --------------------------------------- | -------- | ------------------ | +|----------------|-----------------------------------------|----------|--------------------| | `[]byte{0xf7}` | Latest height a batch slashing occurred | `uint64` | Big endian encoded | ### LastUnbondingBlockHeight @@ -165,15 +173,15 @@ Represents the latest slashed block height. There is always only a singe value s Represents the latest bloch height at which a `Validator` started unbonding from the `Validator Set`. Used to determine slashing conditions. | Key | Value | Type | Encoding | -| -------------- | ---------------------------------------------------- | -------- | ------------------ | +|----------------|------------------------------------------------------|----------|--------------------| | `[]byte{0xf8}` | Latest height at which a Validator started unbonding | `uint64` | Big endian encoded | ### TokenContract & Denom -A denom that is originally from a counter chain will be from a contract. The token contract and denom are stored in two ways. First, the denom is used as the key and the value is the token contract. Second, the contract is used as the key, the value is the denom the token contract represents. +A denom that is originally from a counter chain will be from a contract. The token contract and denom are stored in two ways. First, the denom is used as the key and the value is the token contract. Second, the contract is used as the key, the value is the denom the token contract represents. | Key | Value | Type | Encoding | -| -------------------------------------- | ---------------------- | -------- | --------------------- | +|----------------------------------------|------------------------|----------|-----------------------| | `[]byte{0xf3} + []byte(denom)` | Token contract address | `[]byte` | stored in byte format | | `[]byte{0xf4} + []byte(tokenContract)` | Token denom | `[]byte` | stored in byte format | @@ -182,15 +190,16 @@ A denom that is originally from a counter chain will be from a contract. The tok This entry represents the last observed Valset that was successfully relayed to Ethereum. Updates after an attestation of `ValsetUpdatedEvent` has been processed on Injective. | Key | Value | Type | Encoding | -| -------------- | -------------------------------- | -------------- | ---------------- | +|----------------|----------------------------------|----------------|------------------| | `[]byte{0xfa}` | Last observed Valset on Ethereum | `types.Valset` | Protobuf encoded | + ### LastEventNonce The nonce of the last observed event on Ethereum. This is set when `TryAttestation()` is called. There is always only a single value held in this store. | Key | Value | Type | Encoding | -| -------------- | ------------------------- | -------- | ------------------ | +|----------------|---------------------------|----------|--------------------| | `[]byte{0xf2}` | Last observed event nonce | `uint64` | Big endian encoded | ### LastObservedEthereumHeight @@ -198,9 +207,10 @@ The nonce of the last observed event on Ethereum. This is set when `TryAttestati This block height of the last observed event on Ethereum. There will always only be a single value stored in this store. | Key | Value | Type | Encoding | -| -------------- | ----------------------------- | -------- | ---------------- | +|----------------|-------------------------------|----------|------------------| | `[]byte{0xf9}` | Last observed Ethereum Height | `uint64` | Protobuf encoded | + ### LastEventByValidator This is the last observed event on Ethereum from a particular `Validator`. Updated every time the asssociated `Orchestrator` sends an event claim. @@ -213,9 +223,10 @@ type LastClaimEvent struct { ``` | Key | Value | Type | Encoding | -| ------------------------------------------ | ------------------------------------- | ---------------------- | ---------------- | +|--------------------------------------------|---------------------------------------|------------------------|------------------| | `[]byte{0xf1} + []byte(validator address)` | Last observed event by some Validator | `types.LastClaimEvent` | Protobuf encoded | + ### Attestation Attestation is an aggregate of claims that eventually becomes observed by all orchestrators as more votes (claims) are coming in. Once observed the claim's particular logic gets executed. @@ -230,24 +241,25 @@ type Attestation struct { Claim *types.Any } ``` - | Key | Value | Type | Encoding | -| -------------------------------------------------------------------- | ------------------------------------- | ------------------- | ---------------- | +|----------------------------------------------------------------------|---------------------------------------|---------------------|------------------| | `[]byte{0x5} + event nonce (big endian encoded) + []byte(claimHash)` | Attestation of occurred events/claims | `types.Attestation` | Protobuf encoded | ### PastEthSignatureCheckpoint -A computed hash indicating that a validator set/token batch in fact existed on Injective. This checkpoint also exists in `Peggy contract`.\ -Updated on each new valset update and token batch creation. +A computed hash indicating that a validator set/token batch in fact existed on Injective. This checkpoint also exists in `Peggy contract`. +Updated on each new valset update and token batch creation. + | Key | Value | Type | Encoding | -| -------------- | ----------------------------------------- | ----------------- | -------------------- | +|----------------|-------------------------------------------|-------------------|----------------------| | `[]byte{0x1b}` | Last created checkpoint hash on Injective | `gethcommon.Hash` | store in byte format | ### EthereumBlacklist A list of known malicious Ethereum addresses that are prevented from using the bridge. -| Key | Value | Type | Encoding | -| ----------------------------------------- | ------------------- | ----------------- | ---------------------- | -| `[]byte{0x1c} + []byte(ethereum address)` | Empty \[]byte slice | `gethcommon.Hash` | stored in byte format] | +| Key | Value | Type | Encoding | +|-------------------------------------------|--------------------|-------------------|------------------------| +| `[]byte{0x1c} + []byte(ethereum address)` | Empty []byte slice | `gethcommon.Hash` | stored in byte format] | + diff --git a/.gitbook/developers-native/injective/peggy/04_messages.mdx b/.gitbook/developers-native/injective/peggy/04_messages.md similarity index 92% rename from .gitbook/developers-native/injective/peggy/04_messages.mdx rename to .gitbook/developers-native/injective/peggy/04_messages.md index 15c2a58..d2f1451 100644 --- a/.gitbook/developers-native/injective/peggy/04_messages.mdx +++ b/.gitbook/developers-native/injective/peggy/04_messages.md @@ -5,15 +5,15 @@ title: Messages # Messages -This is a reference document for Peggy message types. For code reference and exact arguments see the [proto definitions](https://github.com/InjectiveLabs/injective-core/blob/master/proto/injective/peggy/v1/msgs.proto). +This is a reference document for Peggy message types. For code reference and exact arguments see the [proto definitions](https://github.com/InjectiveLabs/injective-core/blob/master/proto/injective/peggy/v1/msgs.proto). ## User messages -These are messages sent on the Injective Chain peggy module by the end user. See [workflow](02_workflow.md) for a more detailed summary of the entire deposit and withdraw process. +These are messages sent on the Injective Chain peggy module by the end user. See [workflow](./02_workflow.md) for a more detailed summary of the entire deposit and withdraw process. ### SendToEth -Sent to Injective whenever a user wishes to make a withdrawal back to Ethereum. Submitted amount is removed from the user's balance immediately.\ +Sent to Injective whenever a user wishes to make a withdrawal back to Ethereum. Submitted amount is removed from the user's balance immediately. The withdrawal is added to the outgoing tx pool as a `types.OutgoingTransferTx` where it will remain until it is included in a batch. ```go @@ -36,7 +36,7 @@ type MsgCancelSendToEth struct { Sender string // original sender of the withdrawal } -``` +``` ### SubmitBadSignatureEvidence @@ -56,10 +56,11 @@ These messages are sent by the `Batch Creator` subprocess of `peggo` ### RequestBatch -This message is sent whenever some `Batch Creator` finds pooled withdrawals that when batched would satisfy their minimum batch fee (`PEGGO_MIN_BATCH_FEE_USD`).\ -After receiving this message the `Peggy module` collects all withdrawals of the requested token denom, creates a unique token batch (`types.OutgoingTxBatch`) and places it in the `Outgoing Batch pool`.\ +This message is sent whenever some `Batch Creator` finds pooled withdrawals that when batched would satisfy their minimum batch fee (`PEGGO_MIN_BATCH_FEE_USD`). +After receiving this message the `Peggy module` collects all withdrawals of the requested token denom, creates a unique token batch (`types.OutgoingTxBatch`) and places it in the `Outgoing Batch pool`. Withdrawals that are batched cannot be cancelled with `MsgCancelSendToEth`. + ```go type MsgRequestBatch struct { Orchestrator string // orchestrator address interested in creating the batch. Not permissioned. @@ -67,14 +68,15 @@ type MsgRequestBatch struct { } ``` + ## Oracle Messages These messages are sent by the `Oracle` subprocess of `peggo` ### DepositClaim -Sent to Injective when a `SendToInjectiveEvent` is emitted from the `Peggy contract`.\ -This occurs whenever a user is making an individual deposit from Ethereum to Injective. +Sent to Injective when a `SendToInjectiveEvent` is emitted from the `Peggy contract`. +This occurs whenever a user is making an individual deposit from Ethereum to Injective. ```go type MsgDepositClaim struct { @@ -90,7 +92,7 @@ type MsgDepositClaim struct { ### WithdrawClaim -Sent to Injective when a `TransactionBatchExecutedEvent` is emitted from the `Peggy contract`.\ +Sent to Injective when a `TransactionBatchExecutedEvent` is emitted from the `Peggy contract`. This occurs when a `Relayer` has successfully called `submitBatch` on the contract to complete a batch of withdrawals. ```go @@ -105,7 +107,7 @@ type MsgWithdrawClaim struct { ### ValsetUpdatedClaim -Sent to Injective when a `ValsetUpdatedEvent` is emitted from the `Peggy contract`.\ +Sent to Injective when a `ValsetUpdatedEvent` is emitted from the `Peggy contract`. This occurs when a `Relayer` has successfully called `updateValset` on the contract to update the `Validator Set` on Ethereum. ```go @@ -123,8 +125,8 @@ type MsgValsetUpdatedClaim struct { ### ERC20DeployedClaim -Sent to Injective when a `ERC20DeployedEvent` is emitted from the `Peggy contract`.\ -This occurs whenever the `deployERC20` method is called on the contract to issue a new token asset eligible for bridging. +Sent to Injective when a `ERC20DeployedEvent` is emitted from the `Peggy contract`. +This occurs whenever the `deployERC20` method is called on the contract to issue a new token asset eligible for bridging. ```go type MsgERC20DeployedClaim struct { @@ -139,14 +141,15 @@ type MsgERC20DeployedClaim struct { } ``` + ## Signer Messages These messages are sent by the `Signer` subprocess of `peggo` ### ConfirmBatch -When `Signer` finds a batch that the `Orchestrator` (`Validator`) has not signed off, it constructs a signature with its `Delegated Ethereum Key` and sends the confirmation to Injective.\ -It's crucial that a `Validator` eventually provides their confirmation for a created batch as they will be slashed otherwise. +When `Signer` finds a batch that the `Orchestrator` (`Validator`) has not signed off, it constructs a signature with its `Delegated Ethereum Key` and sends the confirmation to Injective. +It's crucial that a `Validator` eventually provides their confirmation for a created batch as they will be slashed otherwise. ```go type MsgConfirmBatch struct { @@ -160,7 +163,7 @@ type MsgConfirmBatch struct { ### ValsetConfirm -When `Signer` finds a valset update that the `Orchestrator` (`Validator`) has not signed off, it constructs a signature with its `Delegated Ethereum Key` and sends the confirmation to Injective.\ +When `Signer` finds a valset update that the `Orchestrator` (`Validator`) has not signed off, it constructs a signature with its `Delegated Ethereum Key` and sends the confirmation to Injective. It's crucial that a `Validator` eventually provides their confirmation for a created valset update as they will be slashed otherwise. ```go @@ -182,8 +185,8 @@ These are messages sent directly using the validator's message key. ### SetOrchestratorAddresses -Sent to Injective by an `Operator` managing a `Validator` node. Before being able to start their `Orchestrator` (`peggo`) process, they must register a chosen Ethereum address to represent their `Validator` on Ethereum.\ -Optionally, an additional Injective address can be provided (`Orchestrator` field) to represent that `Validator` in the bridging process (`peggo`). Defaults to `Validator`'s own address if omitted. +Sent to Injective by an `Operator` managing a `Validator` node. Before being able to start their `Orchestrator` (`peggo`) process, they must register a chosen Ethereum address to represent their `Validator` on Ethereum. +Optionally, an additional Injective address can be provided (`Orchestrator` field) to represent that `Validator` in the bridging process (`peggo`). Defaults to `Validator`'s own address if omitted. ```go type MsgSetOrchestratorAddresses struct { @@ -192,5 +195,5 @@ type MsgSetOrchestratorAddresses struct { EthAddress string // the Sender's (Validator) delegated Ethereum address } ``` +This message sets the Orchestrator's delegate keys. -This message sets the Orchestrator's delegate keys. diff --git a/.gitbook/developers-native/injective/peggy/05_slashing.mdx b/.gitbook/developers-native/injective/peggy/05_slashing.md similarity index 98% rename from .gitbook/developers-native/injective/peggy/05_slashing.mdx rename to .gitbook/developers-native/injective/peggy/05_slashing.md index b71901d..41d2fa4 100644 --- a/.gitbook/developers-native/injective/peggy/05_slashing.mdx +++ b/.gitbook/developers-native/injective/peggy/05_slashing.md @@ -4,11 +4,10 @@ title: Slashing --- # Slashing - ### Security Concerns -The **Validator Set** is the actual set of keys with stake behind them, which are slashed for double-signs or other\ -misbehavior. We typically consider the security of a chain to be the security of a _Validator Set_. This varies on\ +The **Validator Set** is the actual set of keys with stake behind them, which are slashed for double-signs or other +misbehavior. We typically consider the security of a chain to be the security of a _Validator Set_. This varies on each chain, but is our gold standard. Even IBC offers no more security than the minimum of both involved Validator Sets. The **Eth bridge relayer** is a binary run alongside the main `injectived` daemon by the validator set. It exists purely as a matter of code organization and is in charge of signing Ethereum transactions, as well as observing events on Ethereum and bringing them into the Injective Chain state. It signs transactions bound for Ethereum with an Ethereum key, and signs over events coming from Ethereum with an Injective Chain account key. We can add slashing conditions to any mis-signed message by any _Eth Signer_ run by the _Validator Set_ and be able to provide the same security as the _Validator Set_, just a different module detecting evidence of malice and deciding how much to slash. If we can prove a transaction signed by any _Eth Signer_ of the _Validator Set_ was illegal or malicious, then we can slash on the Injective Chain side and potentially provide 100% of the security of the _Validator Set_. Note that this also has access to the 3 week unbonding period to allow evidence to slash even if they immediately unbond. @@ -18,7 +17,6 @@ Below are various slashing conditions we use in Peggy. ## PEGGYSLASH-01: Signing fake validator set or tx batch evidence This slashing condition is intended to stop validators from signing over a validator set and nonce that has never existed on the Injective Chain. It works via an evidence mechanism, where anyone can submit a message containing the signature of a validator over a fake validator set. This is intended to produce the effect that if a cartel of validators is formed with the intention of submitting a fake validator set, one defector can cause them all to be slashed. - ```go // This call allows anyone to submit evidence that a // validator has signed a valset, batch, or logic call that never @@ -29,7 +27,6 @@ type MsgSubmitBadSignatureEvidence struct { Sender string } ``` - **Implementation considerations:** The trickiest part of this slashing condition is determining that a validator set has never existed on Injective. To save space, we will need to clean up old validator sets. We could keep a mapping of validator set hash to true in the KV store, and use that to check if a validator set has ever existed. This is more efficient than storing the whole validator set, but its growth is still unbounded. It might be possible to use other cryptographic methods to cut down on the size of this mapping. It might be OK to prune very old entries from this mapping, but any pruning reduces the deterrence of this slashing condition. @@ -51,7 +48,7 @@ This slashing condition is triggered when a validator does not sign a transactio ## PEGGYSLASH-03: Failure to sign validator set update -This slashing condition is triggered when a validator does not sign a validator set update which is produced by the Peggy module. This prevents two bad scenarios- +This slashing condition is triggered when a validator does not sign a validator set update which is produced by the Peggy module. This prevents two bad scenarios- 1. A validator simply does not bother to keep the correct binaries running on their system, 2. A cartel of >1/3 validators unbond and then refuse to sign updates, preventing any validator set updates from getting enough signatures to be submitted to the Peggy Ethereum contract. If they prevent validator set updates for longer than the Injective Chain unbonding period, they can no longer be punished for submitting fake validator set updates and tx batches (PEGGYSLASH-01 and PEGGYSLASH-03). @@ -91,3 +88,4 @@ Unfortunately, PEGGYSLASH-05 has the same downsides as PEGGYSLASH-04 in that it PEGGYSLASH-05 also introduces significant risks. Mostly around forks on the Ethereum chain. For example recently OpenEthereum failed to properly handle the Berlin hardfork, the resulting node 'failure' was totally undetectable to automated tools. It didn't crash so there was no restart to perform, blocks where still being produced although extremely slowly. If this had occurred while Peggy was running with PEGGYSLASH-05 active it would have caused those validators to be removed from the set. Possibly resulting in a very chaotic moment for the chain as dozens of validators where removed for little to no fault of their own. Without PEGGYSLASH-04 and PEGGYSLASH-05, the Ethereum event oracle only continues to function if >2/3 of the validators voluntarily submit correct claims. Although the arguments against PEGGYSLASH-04 and PEGGYSLASH-05 are convincing, we must decide whether we are comfortable with this fact. Alternatively we must be comfortable with the Injective Chain potentially halting entirely due to Ethereum generated factors. + diff --git a/.gitbook/developers-native/injective/peggy/06_end_block.mdx b/.gitbook/developers-native/injective/peggy/06_end_block.md similarity index 93% rename from .gitbook/developers-native/injective/peggy/06_end_block.mdx rename to .gitbook/developers-native/injective/peggy/06_end_block.md index f15a76b..40bcae0 100644 --- a/.gitbook/developers-native/injective/peggy/06_end_block.mdx +++ b/.gitbook/developers-native/injective/peggy/06_end_block.md @@ -3,30 +3,29 @@ sidebar_position: 5 title: End-Block --- -# EndBlock +# EndBlocker -Upon the end of each block the following operations are performed to the state of the module +Upon the end of each block the following operations are performed to the state of the module ## 1. Slashing ### Validator slashing -A validator is slashed for not signing over a valset update which passed the `SignedValsetsWindow`.\ +A validator is slashed for not signing over a valset update which passed the `SignedValsetsWindow`. In other words, if a validator fails to provide the confirmation for a valset update within a preconfigured amount of time, they will be slashed for `SlashFractionValset` portion of their stake and get jailed immediately. ### Batch Slashing -A validator is slashed for not signing over a batch which passed the `SignedBatchesWindow`.\ +A validator is slashed for not signing over a batch which passed the `SignedBatchesWindow`. In other words, if a validator fails to provide the confirmation for a batch within a preconfigured amount of time, they will be slashed for `SlashFractionBatch` portion of their stake and get jailed immediately. ## 2. Cancelling timed out batches -Any batch still present in the `Outgoing Batch pool` whose `BatchTimeout` (a designated Ethereum height by which the batch should have executed) is exceeded gets removed from the pool and the withdrawals are reinserted back into the `Outgoing Tx pool`. +Any batch still present in the `Outgoing Batch pool` whose `BatchTimeout` (a designated Ethereum height by which the batch should have executed) is exceeded gets removed from the pool and the withdrawals are reinserted back into the `Outgoing Tx pool`. ## 3. Creating new Valset updates A new `Validator Set` update will be created automatically when: - * there is a power diff greater than 5% between the latest and current validator set * a validator begins unbonding @@ -38,11 +37,10 @@ Previously observed valsets that passed the `SignedValsetsWindow` are removed fr ## 5. Attestation processing -Processes all attestations (an aggregate of claims for a particular event) currently being voted on. Each attestation is processed one by one to ensure each `Peggy contract` event is processed.\ +Processes all attestations (an aggregate of claims for a particular event) currently being voted on. Each attestation is processed one by one to ensure each `Peggy contract` event is processed. After each processed attestation the module's `lastObservedEventNonce` and `lastObservedEthereumBlockHeight` are updated. Depending on the type of claim in the attestation, the following is executed: - * `MsgDepositClaim`: deposited tokens are minted/unlocked for the receiver address * `MsgWithdrawClaim`: corresponding batch is removed from the outgoing pool and any previous batch is cancelled * `MsgValsetUpdatedClaim`: the module's `LastObservedValset` is updated diff --git a/.gitbook/developers-native/injective/peggy/07_events.md b/.gitbook/developers-native/injective/peggy/07_events.md new file mode 100644 index 0000000..d29a560 --- /dev/null +++ b/.gitbook/developers-native/injective/peggy/07_events.md @@ -0,0 +1,143 @@ +--- +sidebar_position: 7 +title: Events +--- + +# Events + +The peggy module emits the following events: + +## EndBlocker + +### EventAttestationObserved +| Type | Attribute Key | Attribute Value | +|--------|------------------|---------------------------| +| int32 | attestation_type | `{attestation_type}` | +| string | bridge_contract | `{bridge_contract_address}` | +| uint64 | bridge_chain_id | `{bridge_chain_id}` | +| []byte | attestation_id | `{attestation_id}` | +| uint64 | nonce | `{event_nonce}` | + +### EventValidatorSlash +| Type | Attribute Key | Attribute Value | +|--------|-------------------|-----------------------| +| string | reason | `{reason_for_slashing}` | +| int64 | power | `{validator_power}` | +| string | consensus_address | `{consensus_addr}` | +| string | operator_address | `{operator_addr}` | +| string | moniker | `{validator_moniker}` | + + +## Handler + +### EventSetOrchestratorAddresses + +| Type | Attribute Key | Attribute Value | +|--------|----------------------|---------------------| +| string | validator_address | `{validator_addr}` | +| string | orchestrator_address | `{orchestrator_addr}` | +| string | operator_eth_address | `{eth_addr}` | + +### EventSendToEth + +| Type | Attribute Key | Attribute Value | +|----------|----------------|-----------------| +| message | outgoing_tx_id | `{tx_id}` | +| string | sender | `{sender_addr}` | +| string | receiver | `{dest_addr}` | +| sdk.Coin | amount | `{token_amount}` | +| sdk.Coin | bridge_fee | `{token_amount}` | + + +### EventBridgeWithdrawCanceled +| Type | Attribute Key | Attribute Value | +|----------------------|-----------------|-------------------| +| withdrawal_cancelled | bridge_contract | `{bridge_contract}` | +| withdrawal_cancelled | bridge_chain_id | `{bridge_chain_id}` | + + +### EventOutgoingBatch + +| Type | Attribute Key | Attribute Value | +|----------|----------------------|-----------------| +| string | denom | `{token_denom}` | +| string | orchestrator_address | `{orch_addr}` | +| uint64 | batch_nonce | `{batch_nonce}` | +| uint64 | batch_timeout | `{block_height}` | +| []uint64 | batch_tx_ids | `{ids}` | + +### EventOutgoingBatchCanceled +| Type | Attribute Key | Attribute Value | +|--------|-----------------|-------------------| +| string | bridge_contract | `{bridge_contract}` | +| uint64 | bridge_chain_id | `{bridge_chain_id}` | +| uint64 | batch_id | `{id}` | +| uint64 | nonce | `{nonce}` | + +### EventValsetConfirm + +| Type | Attribute Key | Attribute Value | +|--------|----------------------|-----------------| +| uint64 | valset_nonce | `{nonce}` | +| string | orchestrator_address | `{prch_addr}` | + + +### EventConfirmBatch + +| Type | Attribute Key | Attribute Value | +|--------|----------------------|-----------------| +| uint64 | batch_nonce | `{nonce}` | +| string | orchestrator_address | `{orch_addr}` | + +### EventDepositClaim + +| Type | Attribute Key | Attribute Value | +|---------|----------------------|-------------------| +| uint64 | event_nonce | `{event_nonce}` | +| uint64 | event_height | `{event_height}` | +| []byte | attestation_id | `{attestation_key}` | +| string | ethereum_sender | `{sender_addr}` | +| string | cosmos_receiver | `{receiver_addr}` | +| string | token_contract | `{contract_addr}` | +| sdk.Int | amount | `{token_amount}` | +| string | orchestrator_address | `{orch_addr}` | +| string | data | `{custom_data}` | + + +### EventWithdrawClaim + +| Type | Attribute Key | Attribute Value | +|--------|----------------------|-------------------| +| uint64 | event_nonce | `{event_nonce}` | +| uint64 | event_height | `{event_height}` | +| []byte | attestation_id | `{attestation_key}` | +| uint64 | batch_nonce | `{batch_nonce}` | +| string | token_contract | `{contract_addr}` | +| string | orchestrator_address | `{orch_addr}` | + +### EventERC20DeployedClaim +| Type | Attribute Key | Attribute Value | +|--------|----------------------|------------------------| +| uint64 | event_nonce | `{event_nonce}` | +| uint64 | event_height | `{event_height}` | +| []byte | attestation_id | `{attestation_key}` | +| string | cosmos_denom | `{token_denom}` | +| string | token_contract | `{token_conntract_addr}` | +| string | name | `{token_name}` | +| string | symbol | `{token_symbol}` | +| uint64 | decimals | `{token_decimals}` | +| string | orchestrator_address | `{orch_addr}` | + +### EventValsetUpdateClaim +| Type | Attribute Key | Attribute Value | +|--------------------|----------------------|-----------------------| +| uint64 | event_nonce | `{event_nonce}` | +| uint64 | event_height | `{event_height}` | +| []byte | attestation_id | `{attestation_key}` | +| uint64 | valset_nonce | `{valset_nonce}` | +| []*BridgeValidator | valset_members | `{array_of_validators}` | +| sdk.Int | reward_amount | `{amount}` | +| string | reward_token | `{contract_addr}` | +| string | orchestrator_address | `{orch_addr}` | + + diff --git a/.gitbook/developers-native/injective/peggy/07_events.mdx b/.gitbook/developers-native/injective/peggy/07_events.mdx deleted file mode 100644 index 3e2c40e..0000000 --- a/.gitbook/developers-native/injective/peggy/07_events.mdx +++ /dev/null @@ -1,143 +0,0 @@ ---- -sidebar_position: 7 -title: Events ---- - -# Events - -The peggy module emits the following events: - -## EndBlocker - -### EventAttestationObserved -| Type | Attribute Key | Attribute Value | -|--------|------------------|---------------------------| -| int32 | attestation_type | {attestation_type} | -| string | bridge_contract | {bridge_contract_address} | -| uint64 | bridge_chain_id | {bridge_chain_id} | -| []byte | attestation_id | {attestation_id} | -| uint64 | nonce | {event_nonce} | - -### EventValidatorSlash -| Type | Attribute Key | Attribute Value | -|--------|-------------------|-----------------------| -| string | reason | {reason_for_slashing} | -| int64 | power | {validator_power} | -| string | consensus_address | {consensus_addr} | -| string | operator_address | {operator_addr} | -| string | moniker | {validator_moniker} | - - -## Handler - -### EventSetOrchestratorAddresses - -| Type | Attribute Key | Attribute Value | -|--------|----------------------|---------------------| -| string | validator_address | {validator_addr} | -| string | orchestrator_address | {orchestrator_addr} | -| string | operator_eth_address | {eth_addr} | - -### EventSendToEth - -| Type | Attribute Key | Attribute Value | -|----------|----------------|-----------------| -| message | outgoing_tx_id | {tx_id} | -| string | sender | {sender_addr} | -| string | receiver | {dest_addr} | -| sdk.Coin | amount | {token_amount} | -| sdk.Coin | bridge_fee | {token_amount} | - - -### EventBridgeWithdrawCanceled -| Type | Attribute Key | Attribute Value | -|----------------------|-----------------|-------------------| -| withdrawal_cancelled | bridge_contract | {bridge_contract} | -| withdrawal_cancelled | bridge_chain_id | {bridge_chain_id} | - - -### EventOutgoingBatch - -| Type | Attribute Key | Attribute Value | -|----------|----------------------|-----------------| -| string | denom | {token_denom} | -| string | orchestrator_address | {orch_addr} | -| uint64 | batch_nonce | {batch_nonce} | -| uint64 | batch_timeout | {block_height} | -| []uint64 | batch_tx_ids | {ids} | - -### EventOutgoingBatchCanceled -| Type | Attribute Key | Attribute Value | -|--------|-----------------|-------------------| -| string | bridge_contract | {bridge_contract} | -| uint64 | bridge_chain_id | {bridge_chain_id} | -| uint64 | batch_id | {id} | -| uint64 | nonce | {nonce} | - -### EventValsetConfirm - -| Type | Attribute Key | Attribute Value | -|--------|----------------------|-----------------| -| uint64 | valset_nonce | {nonce} | -| string | orchestrator_address | {prch_addr} | - - -### EventConfirmBatch - -| Type | Attribute Key | Attribute Value | -|--------|----------------------|-----------------| -| uint64 | batch_nonce | {nonce} | -| string | orchestrator_address | {orch_addr} | - -### EventDepositClaim - -| Type | Attribute Key | Attribute Value | -|---------|----------------------|-------------------| -| uint64 | event_nonce | {event_nonce} | -| uint64 | event_height | {event_height} | -| []byte | attestation_id | {attestation_key} | -| string | ethereum_sender | {sender_addr} | -| string | cosmos_receiver | {receiver_addr} | -| string | token_contract | {contract_addr} | -| sdk.Int | amount | {token_amount} | -| string | orchestrator_address | {orch_addr} | -| string | data | {custom_data} | - - -### EventWithdrawClaim - -| Type | Attribute Key | Attribute Value | -|--------|----------------------|-------------------| -| uint64 | event_nonce | {event_nonce} | -| uint64 | event_height | {event_height} | -| []byte | attestation_id | {attestation_key} | -| uint64 | batch_nonce | {batch_nonce} | -| string | token_contract | {contract_addr} | -| string | orchestrator_address | {orch_addr} | - -### EventERC20DeployedClaim -| Type | Attribute Key | Attribute Value | -|--------|----------------------|------------------------| -| uint64 | event_nonce | {event_nonce} | -| uint64 | event_height | {event_height} | -| []byte | attestation_id | {attestation_key} | -| string | cosmos_denom | {token_denom} | -| string | token_contract | {token_conntract_addr} | -| string | name | {token_name} | -| string | symbol | {token_symbol} | -| uint64 | decimals | {token_decimals} | -| string | orchestrator_address | {orch_addr} | - -### EventValsetUpdateClaim -| Type | Attribute Key | Attribute Value | -|--------------------|----------------------|-----------------------| -| uint64 | event_nonce | {event_nonce} | -| uint64 | event_height | {event_height} | -| []byte | attestation_id | {attestation_key} | -| uint64 | valset_nonce | {valset_nonce} | -| []*BridgeValidator | valset_members | {array_of_validators} | -| sdk.Int | reward_amount | {amount} | -| string | reward_token | {contract_addr} | -| string | orchestrator_address | {orch_addr} | - - diff --git a/.gitbook/developers-native/injective/peggy/08_params.mdx b/.gitbook/developers-native/injective/peggy/08_params.md similarity index 88% rename from .gitbook/developers-native/injective/peggy/08_params.mdx rename to .gitbook/developers-native/injective/peggy/08_params.md index 19d7a54..d76128c 100644 --- a/.gitbook/developers-native/injective/peggy/08_params.mdx +++ b/.gitbook/developers-native/injective/peggy/08_params.md @@ -35,26 +35,26 @@ type Params struct { ## `peggy_id` -A random 32 byte value to prevent signature reuse, for example if the\ -Injective Chain validators decided to use the same Ethereum keys for another chain\ -also running Peggy we would not want it to be possible to play a deposit\ -from chain A back on chain B's Peggy. This value IS USED ON ETHEREUM so\ -it must be set in your genesis.json before launch and not changed after\ -deploying Peggy. Changing this value after deploying Peggy will result\ -in the bridge being non-functional. To recover just set it back to the original\ +A random 32 byte value to prevent signature reuse, for example if the +Injective Chain validators decided to use the same Ethereum keys for another chain +also running Peggy we would not want it to be possible to play a deposit +from chain A back on chain B's Peggy. This value IS USED ON ETHEREUM so +it must be set in your genesis.json before launch and not changed after +deploying Peggy. Changing this value after deploying Peggy will result +in the bridge being non-functional. To recover just set it back to the original value the contract was deployed with. ## `contract_source_hash` -The code hash of a known good version of the Peggy contract\ -solidity code. This can be used to verify the correct version\ -of the contract has been deployed. This is a reference value for\ +The code hash of a known good version of the Peggy contract +solidity code. This can be used to verify the correct version +of the contract has been deployed. This is a reference value for governance action only it is never read by any Peggy code ## `bridge_ethereum_address` -is address of the bridge contract on the Ethereum side, this is a\ -reference value for governance only and is not actually used by any\ +is address of the bridge contract on the Ethereum side, this is a +reference value for governance only and is not actually used by any Peggy module code. The Ethereum bridge relayer use this value to interact with Peggy contract for querying events and submitting valset/batches to Peggy contract. @@ -71,18 +71,18 @@ These reference values may be used by future Peggy client implementations to all * `signed_batches_window` * `signed_claims_window` -These values represent the time in blocks that a validator has to submit\ -a signature for a batch or valset, or to submit a claim for a particular\ +These values represent the time in blocks that a validator has to submit +a signature for a batch or valset, or to submit a claim for a particular attestation nonce. -In the case of attestations this clock starts when the\ -attestation is created, but only allows for slashing once the event has passed.\ -Note that that claims slashing is not currently enabled see [slashing spec](05_slashing.md) +In the case of attestations this clock starts when the +attestation is created, but only allows for slashing once the event has passed. +Note that that claims slashing is not currently enabled see [slashing spec](./05_slashing.md) ## `target_batch_timeout` -This is the 'target' value for when batches time out, this is a target because\ -Ethereum is a probabilistic chain and you can't say for sure what the block\ +This is the 'target' value for when batches time out, this is a target because +Ethereum is a probabilistic chain and you can't say for sure what the block frequency is ahead of time. ## Ethereum timing @@ -90,9 +90,9 @@ frequency is ahead of time. * `average_block_time` * `average_ethereum_block_time` -These values are the average Injective Chain block time and Ethereum block time respectively\ -and they are used to compute what the target batch timeout is. It is important that\ -governance updates these in case of any major, prolonged change in the time it takes\ +These values are the average Injective Chain block time and Ethereum block time respectively +and they are used to compute what the target batch timeout is. It is important that +governance updates these in case of any major, prolonged change in the time it takes to produce a block ## Slash fractions @@ -102,11 +102,11 @@ to produce a block * `slash_fraction_claim` * `slash_fraction_conflicting_claim` -The slashing fractions for the various peggy related slashing conditions. The first three\ +The slashing fractions for the various peggy related slashing conditions. The first three refer to not submitting a particular message, the third for failing to submit a claim and the last for submitting a different claim than other validators. -Note that claim slashing is currently disabled as outlined in the [slashing spec](05_slashing.md) +Note that claim slashing is currently disabled as outlined in the [slashing spec](./05_slashing.md) ## `valset_reward` -Valset reward is the reward amount paid to a relayer when they relay a valset to the Peggy contract on Ethereum. +Valset reward is the reward amount paid to a relayer when they relay a valset to the Peggy contract on Ethereum. \ No newline at end of file diff --git a/.gitbook/developers-native/injective/peggy/09_relay_semantics.mdx b/.gitbook/developers-native/injective/peggy/09_relay_semantics.md similarity index 100% rename from .gitbook/developers-native/injective/peggy/09_relay_semantics.mdx rename to .gitbook/developers-native/injective/peggy/09_relay_semantics.md diff --git a/.gitbook/developers-native/injective/peggy/10_future_improvements.mdx b/.gitbook/developers-native/injective/peggy/10_future_improvements.md similarity index 100% rename from .gitbook/developers-native/injective/peggy/10_future_improvements.mdx rename to .gitbook/developers-native/injective/peggy/10_future_improvements.md diff --git a/.gitbook/developers-native/injective/peggy/99_errors.mdx b/.gitbook/developers-native/injective/peggy/99_errors.md similarity index 100% rename from .gitbook/developers-native/injective/peggy/99_errors.mdx rename to .gitbook/developers-native/injective/peggy/99_errors.md diff --git a/.gitbook/developers-native/injective/peggy/index.md b/.gitbook/developers-native/injective/peggy/index.md new file mode 100644 index 0000000..841e030 --- /dev/null +++ b/.gitbook/developers-native/injective/peggy/index.md @@ -0,0 +1,39 @@ +# `Peggy` + +## Abstract + +The peggy module enables the Injective Chain to support a trustless, on-chain bidirectional ERC-20 token bridge to Ethereum. In this system, +holders of ERC-20 tokens on Ethereum can convert their ERC-20 tokens to Cosmos-native coins on +the Injective Chain and vice-versa. + +This decentralized bridge is secured and operated by the validators of the Injective Chain. + +## Contents + +1. [Definitions](./01_definitions.md) +2. [Workflow](./02_workflow.md) +3. [State](./03_state.md) +4. [Messages](./04_messages.md) +5. [Slashing](./05_slashing.md) +6. [End-Block](./06_end_block.md) +7. [Events](./07_events.md) +8. [Parameters](./08_params.md) + +### Components + +1. **[Peggy](https://etherscan.io/address/0xF955C57f9EA9Dc8781965FEaE0b6A2acE2BAD6f3) smart contract on Ethereum** +2. **Peggy module on the Injective Chain** +3. **[Peggo](https://github.com/InjectiveLabs/peggo) (off-chain relayer aka orchestrator)** + - **Oracle** (Observes events of Peggy contract and send claims to the Peggy module) + - **EthSigner** (Signs Valset and Batch confirmations to the Peggy module) + - **Batch Requester** (Sends batch token withdrawal requests to the Peggy module) + - **Valset Relayer** (Submits Validator set updates to the Peggy contract) + - **Batch Relayer** (Submits batches of token withdrawals to the Peggy contract) + +In addition to running an `injectived` node to sign blocks, Injective Chain validators must also run the `peggo` orchestrator to relay data from the Peggy smart contract on Ethereum and the Peggy module on the Injective Chain. + +### Peggo Functionalities + +1. **Maintaining an up-to-date checkpoint of the Injective Chain validator set on Ethereum** +2. **Transferring ERC-20 tokens from Ethereum to the Injective Chain** +3. **Transferring pegged tokens from the Injective Chain to Ethereum** diff --git a/.gitbook/developers-native/injective/permissions/01_concepts.mdx b/.gitbook/developers-native/injective/permissions/01_concepts.md similarity index 99% rename from .gitbook/developers-native/injective/permissions/01_concepts.mdx rename to .gitbook/developers-native/injective/permissions/01_concepts.md index 63cf5a3..e55d00b 100644 --- a/.gitbook/developers-native/injective/permissions/01_concepts.mdx +++ b/.gitbook/developers-native/injective/permissions/01_concepts.md @@ -44,7 +44,7 @@ At its core, a namespace comprises: - The denomination of the `TokenFactory` asset. The denom in the namespace corresponds to the `TokenFactory` asset with the same name, of which the creator of the namespace is also the admin of the `TokenFactory` asset -![image.png](NamespaceRoleCreationPermissionsFlow.png) +![image.png](./NamespaceRoleCreationPermissionsFlow.png) **Actions** @@ -110,7 +110,7 @@ At its core, a namespace comprises: - Role actors are permitted to execute any action for which any of their roles allow - For example, if role ABC had permissions to mint, send, and receive, then any role actor with role ABC would be permitted to `mint`, `send`, and `receive` the namespace asset. Suppose role XYZ had `burn` and `mint` permissions, and an actor had role ABC as well as XYZ. Then the actor would be permitted to `mint`, `send`, `receive`, and `burn` the asset. -![image.png](PolicyManagers.png) +![image.png](./PolicyManagers.png) **Policy Statuses** diff --git a/.gitbook/developers-native/injective/permissions/02_state.mdx b/.gitbook/developers-native/injective/permissions/02_state.md similarity index 100% rename from .gitbook/developers-native/injective/permissions/02_state.mdx rename to .gitbook/developers-native/injective/permissions/02_state.md diff --git a/.gitbook/developers-native/injective/permissions/03_state_transitions.mdx b/.gitbook/developers-native/injective/permissions/03_state_transitions.md similarity index 100% rename from .gitbook/developers-native/injective/permissions/03_state_transitions.mdx rename to .gitbook/developers-native/injective/permissions/03_state_transitions.md diff --git a/.gitbook/developers-native/injective/permissions/99_errors.mdx b/.gitbook/developers-native/injective/permissions/99_errors.md similarity index 100% rename from .gitbook/developers-native/injective/permissions/99_errors.mdx rename to .gitbook/developers-native/injective/permissions/99_errors.md diff --git a/.gitbook/developers-native/injective/permissions.mdx b/.gitbook/developers-native/injective/permissions/index.md similarity index 100% rename from .gitbook/developers-native/injective/permissions.mdx rename to .gitbook/developers-native/injective/permissions/index.md diff --git a/.gitbook/developers-native/injective/tokenfactory.mdx b/.gitbook/developers-native/injective/tokenfactory.mdx deleted file mode 100644 index f40e926..0000000 --- a/.gitbook/developers-native/injective/tokenfactory.mdx +++ /dev/null @@ -1,14 +0,0 @@ -# Tokenfactory - -## Abstract - -The tokenfactory module allows for the permissionless creation of new bank denom tokens. - - -## Contents - -1. [Concepts](01_concepts.md) -2. [State](02_state.md) -3. [Messages](03_messages.md) -4. [Events](04_events.md) -5. [Parameters](05_params.md) diff --git a/.gitbook/developers-native/injective/tokenfactory/01_concepts.mdx b/.gitbook/developers-native/injective/tokenfactory/01_concepts.md similarity index 63% rename from .gitbook/developers-native/injective/tokenfactory/01_concepts.mdx rename to .gitbook/developers-native/injective/tokenfactory/01_concepts.md index 7b1bf31..7ac623b 100644 --- a/.gitbook/developers-native/injective/tokenfactory/01_concepts.mdx +++ b/.gitbook/developers-native/injective/tokenfactory/01_concepts.md @@ -5,19 +5,19 @@ title: Concepts # Concepts -The `tokenfactory` module allows any account to create a new token with\ -the name `factory/{creator address}/{subdenom}`. Because tokens are\ -namespaced by creator address, this allows token minting to be\ -permissionless, due to not needing to resolve name collisions. A single\ -account can create multiple denoms, by providing a unique subdenom for each\ -created denom. Once a denom is created, the original creator is given\ +The `tokenfactory` module allows any account to create a new token with +the name `factory/{creator address}/{subdenom}`. Because tokens are +namespaced by creator address, this allows token minting to be +permissionless, due to not needing to resolve name collisions. A single +account can create multiple denoms, by providing a unique subdenom for each +created denom. Once a denom is created, the original creator is given "admin" privileges over the asset. This allows them to: -* Mint their denom to any account -* Burn their denom from any account (if enabled) -* Create a transfer of their denom between any two accounts -* Change the admin. In the future, more admin capabilities may be added. Admins\ - can choose to share admin privileges with other accounts using the authz\ - module. The `ChangeAdmin` functionality, allows changing the master admin\ - account, or even setting it to `""`, meaning no account has admin privileges\ +- Mint their denom to any account +- Burn their denom from any account (if enabled) +- Create a transfer of their denom between any two accounts +- Change the admin. In the future, more admin capabilities may be added. Admins + can choose to share admin privileges with other accounts using the authz + module. The `ChangeAdmin` functionality, allows changing the master admin + account, or even setting it to `""`, meaning no account has admin privileges of the asset. diff --git a/.gitbook/developers-native/injective/tokenfactory/02_state.mdx b/.gitbook/developers-native/injective/tokenfactory/02_state.md similarity index 94% rename from .gitbook/developers-native/injective/tokenfactory/02_state.mdx rename to .gitbook/developers-native/injective/tokenfactory/02_state.md index f504bfa..f872035 100644 --- a/.gitbook/developers-native/injective/tokenfactory/02_state.mdx +++ b/.gitbook/developers-native/injective/tokenfactory/02_state.md @@ -7,13 +7,14 @@ title: State The tokenfactory module keeps state of the following primary objects: -## Denom Authority Metadata +## Denom Authority Metadata -* 0x02 + | + denom + | + 0x01 ⇒ `DenomAuthorityMetadata` +- 0x02 + | + denom + | + 0x01 ⇒ `DenomAuthorityMetadata` ## Denom Creators -* 0x03 + | + creator + | denom ⇒ denom +- 0x03 + | + creator + | denom ⇒ denom + ```protobuf // DenomAuthorityMetadata specifies metadata for addresses that have specific @@ -56,14 +57,12 @@ message GenesisDenom { ]; } ``` - ## Params -`Params` is a module-wide configuration that stores system parameters and defines overall functioning of the tokenfactory module.\ +`Params` is a module-wide configuration that stores system parameters and defines overall functioning of the tokenfactory module. This module is modifiable by governance using params update proposal natively supported by `gov` module. Struct for the `ocr` module params store. - ```protobuf // Params defines the parameters for the tokenfactory module. message Params { diff --git a/.gitbook/developers-native/injective/tokenfactory/03_messages.mdx b/.gitbook/developers-native/injective/tokenfactory/03_messages.md similarity index 71% rename from .gitbook/developers-native/injective/tokenfactory/03_messages.mdx rename to .gitbook/developers-native/injective/tokenfactory/03_messages.md index 4432417..05650bb 100644 --- a/.gitbook/developers-native/injective/tokenfactory/03_messages.mdx +++ b/.gitbook/developers-native/injective/tokenfactory/03_messages.md @@ -10,9 +10,9 @@ In this section we describe the processing of the tokenfactory messages and the ### CreateDenom -Creates a denom of `factory/{creator address}/{subdenom}` given the denom creator\ -address, subdenom and associated metadata (name, symbol, decimals). Subdenoms can contain `[a-zA-Z0-9./]`.`allow_admin_burn` can be set to true to allow the admin to burn tokens from other addresses. - +Creates a denom of `factory/{creator address}/{subdenom}` given the denom creator +address, subdenom and associated metadata (name, symbol, decimals). Subdenoms can contain `[a-zA-Z0-9./]`. +`allow_admin_burn` can be set to true to allow the admin to burn tokens from other addresses. ```protobuf message MsgCreateDenom { string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; @@ -27,18 +27,18 @@ message MsgCreateDenom { **State Modifications:** -* Fund community pool with the denom creation fee from the creator address, set\ +- Fund community pool with the denom creation fee from the creator address, set in `Params`. -* Set `DenomMetaData` via bank keeper. -* Set `AuthorityMetadata` for the given denom to store the admin for the created\ - denom `factory/{creator address}/{subdenom}`. Admin is automatically set as the\ +- Set `DenomMetaData` via bank keeper. +- Set `AuthorityMetadata` for the given denom to store the admin for the created + denom `factory/{creator address}/{subdenom}`. Admin is automatically set as the Msg sender. -* Add denom to the `CreatorPrefixStore`, where a state of denoms created per\ +- Add denom to the `CreatorPrefixStore`, where a state of denoms created per creator is kept. ### Mint -Minting of a specific denom is only allowed for the current admin.\ +Minting of a specific denom is only allowed for the current admin. Note, the current admin is defaulted to the creator of the denom. ```protobuf @@ -53,14 +53,14 @@ message MsgMint { **State Modifications:** -* Safety check the following - * Check that the denom minting is created via `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 +- Safety check the following + - Check that the denom minting is created via `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 ### Burn -Burning of a specific denom is only allowed for the current admin.\ +Burning of a specific denom is only allowed for the current admin. Note, the current admin is defaulted to the creator of the denom. ```protobuf @@ -75,10 +75,10 @@ message MsgBurn { **State Modifications:** -* Safety check the following - * Check that the denom minting is created via `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 +- Safety check the following + - Check that the denom minting is created via `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 ### ChangeAdmin @@ -94,8 +94,8 @@ message MsgChangeAdmin { ### SetDenomMetadata -Setting of metadata for a specific denom is only allowed for the admin of the denom.\ -It allows the overwriting of the denom metadata in the bank module. The admin can also disable the admin burn\ +Setting of metadata for a specific denom is only allowed for the admin of the denom. +It allows the overwriting of the denom metadata in the bank module. The admin can also disable the admin burn capability, if enabled. ```protobuf @@ -119,44 +119,45 @@ message MsgSetDenomMetadata { **State Modifications:** -* Check that sender of the message is the admin of denom -* Modify `AuthorityMetadata` state entry to change the admin of the denom and to potentially disable admin burn capability. +- Check that sender of the message is the admin of denom +- Modify `AuthorityMetadata` state entry to change the admin of the denom and to potentially disable admin burn capability. + ## Expectations from the chain The chain's bech32 prefix for addresses can be at most 16 characters long. -This comes from denoms having a 128 byte maximum length, enforced from the SDK,\ -and us setting longest\_subdenom to be 44 bytes. +This comes from denoms having a 128 byte maximum length, enforced from the SDK, +and us setting longest_subdenom to be 44 bytes. A token factory token's denom is: `factory/{creator address}/{subdenom}` Splitting up into sub-components, this has: -* `len(factory) = 7` -* `2 * len("/") = 2` -* `len(longest_subdenom)` -* `len(creator_address) = len(bech32(longest_addr_length, chain_addr_prefix))`. +- `len(factory) = 7` +- `2 * len("/") = 2` +- `len(longest_subdenom)` +- `len(creator_address) = len(bech32(longest_addr_length, chain_addr_prefix))`. -Longest addr length at the moment is `32 bytes`. Due to SDK error correction\ -settings, this means `len(bech32(32, chain_addr_prefix)) = len(chain_addr_prefix) + 1 + 58`.\ -Adding this all, we have a total length constraint of `128 = 7 + 2 + len(longest_subdenom) + len(longest_chain_addr_prefix) + 1 + 58`.\ +Longest addr length at the moment is `32 bytes`. Due to SDK error correction +settings, this means `len(bech32(32, chain_addr_prefix)) = len(chain_addr_prefix) + 1 + 58`. +Adding this all, we have a total length constraint of `128 = 7 + 2 + len(longest_subdenom) + len(longest_chain_addr_prefix) + 1 + 58`. Therefore `len(longest_subdenom) + len(longest_chain_addr_prefix) = 128 - (7 + 2 + 1 + 58) = 60`. -The choice between how we standardized the split these 60 bytes between maxes\ -from longest\_subdenom and longest\_chain\_addr\_prefix is somewhat arbitrary.\ +The choice between how we standardized the split these 60 bytes between maxes +from longest_subdenom and longest_chain_addr_prefix is somewhat arbitrary. Considerations going into this: -* Per [BIP-0173](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32)\ - the technically longest HRP for a 32 byte address ('data field') is 31 bytes.\ +- Per [BIP-0173](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32) + the technically longest HRP for a 32 byte address ('data field') is 31 bytes. (Comes from encode(data) = 59 bytes, and max length = 90 bytes) -* subdenom should be at least 32 bytes so hashes can go into it -* longer subdenoms are very helpful for creating human readable denoms -* chain addresses should prefer being smaller. The longest HRP in cosmos to date is 11 bytes. (`persistence`) +- subdenom should be at least 32 bytes so hashes can go into it +- longer subdenoms are very helpful for creating human readable denoms +- chain addresses should prefer being smaller. The longest HRP in cosmos to date is 11 bytes. (`persistence`) For explicitness, its currently set to `len(longest_subdenom) = 44` and `len(longest_chain_addr_prefix) = 16`. -Please note, if the SDK increases the maximum length of a denom from 128 bytes,\ +Please note, if the SDK increases the maximum length of a denom from 128 bytes, these caps should increase. So please don't make code rely on these max lengths for parsing. diff --git a/.gitbook/developers-native/injective/tokenfactory/04_events.mdx b/.gitbook/developers-native/injective/tokenfactory/04_events.md similarity index 100% rename from .gitbook/developers-native/injective/tokenfactory/04_events.mdx rename to .gitbook/developers-native/injective/tokenfactory/04_events.md diff --git a/.gitbook/developers-native/injective/tokenfactory/05_params.mdx b/.gitbook/developers-native/injective/tokenfactory/05_params.md similarity index 100% rename from .gitbook/developers-native/injective/tokenfactory/05_params.mdx rename to .gitbook/developers-native/injective/tokenfactory/05_params.md diff --git a/.gitbook/developers-native/injective/tokenfactory/99_errors.mdx b/.gitbook/developers-native/injective/tokenfactory/99_errors.md similarity index 100% rename from .gitbook/developers-native/injective/tokenfactory/99_errors.mdx rename to .gitbook/developers-native/injective/tokenfactory/99_errors.md diff --git a/.gitbook/developers-native/injective/tokenfactory/index.md b/.gitbook/developers-native/injective/tokenfactory/index.md new file mode 100644 index 0000000..d5951e3 --- /dev/null +++ b/.gitbook/developers-native/injective/tokenfactory/index.md @@ -0,0 +1,14 @@ +# Tokenfactory + +## Abstract + +The tokenfactory module allows for the permissionless creation of new bank denom tokens. + + +## Contents + +1. [Concepts](./01_concepts.md) +2. [State](./02_state.md) +3. [Messages](./03_messages.md) +4. [Events](./04_events.md) +5. [Parameters](./05_params.md) diff --git a/.gitbook/developers-native/injective/txfees.mdx b/.gitbook/developers-native/injective/txfees/index.md similarity index 100% rename from .gitbook/developers-native/injective/txfees.mdx rename to .gitbook/developers-native/injective/txfees/index.md diff --git a/.gitbook/developers-native/injective/wasmx/01_concepts.mdx b/.gitbook/developers-native/injective/wasmx/01_concepts.md similarity index 77% rename from .gitbook/developers-native/injective/wasmx/01_concepts.mdx rename to .gitbook/developers-native/injective/wasmx/01_concepts.md index aee3495..50da6d1 100644 --- a/.gitbook/developers-native/injective/wasmx/01_concepts.mdx +++ b/.gitbook/developers-native/injective/wasmx/01_concepts.md @@ -3,24 +3,24 @@ sidebar_position: 1 title: Concepts --- -# Concepts +## Concepts -## Begin blocker execution +### Begin blocker execution -Smart contracts can only respond to incoming messages and do not have the ability to execute actions on their own schedule. The Wasmx module allows contracts to be registered and called in the begin blockers section of each block.\ -To be eligible for this, each registered contract must respond to the sudo message called `begin_blocker` which can only be called by the chain itself and not directly by any user or other contract. This ensures that the "begin\_blocker" message can be trusted. +Smart contracts can only respond to incoming messages and do not have the ability to execute actions on their own schedule. The Wasmx module allows contracts to be registered and called in the begin blockers section of each block. +To be eligible for this, each registered contract must respond to the sudo message called `begin_blocker` which can only be called by the chain itself and not directly by any user or other contract. This ensures that the "begin_blocker" message can be trusted. -## Registration +### Registration Upon registering a contract, the user must declare a gas price, which is the amount they are willing to pay for contract execution, as well as a gas limit, which is the maximum amount of gas that can be consumed during the execution of the contract. Currently, contract registration can only be done through a governance proposal. This proposal, if approved, will add the contract at a specific address to the list of contracts that are run during each "begin blockers" period. -For security reasons, the proposer must specify a code\_id for the contract, which will be verified upon registration and each time the contract is executed. This is to prevent an attacker from registering a benign contract but later upgrading it to a malicious one. The proposer can request to be exempt from this check when registering the contract to avoid delays when a new version of the contract is released, but this may affect the voting results depending on the trustworthiness of the proposer. +For security reasons, the proposer must specify a code_id for the contract, which will be verified upon registration and each time the contract is executed. This is to prevent an attacker from registering a benign contract but later upgrading it to a malicious one. The proposer can request to be exempt from this check when registering the contract to avoid delays when a new version of the contract is released, but this may affect the voting results depending on the trustworthiness of the proposer. The proposer can also request for the contract to be "pinned," meaning it is loaded and kept in memory, which can greatly improve the performance of the contract. -## Deregistration +### Deregistration A contract can be deregistered through a governance proposal, which can be initiated by anyone, including the contract owner if they no longer require the contract or by any other individual if the contract is found to be malicious. @@ -28,26 +28,26 @@ If contract fails to execute due to insufficient gas it will be automatically de When contract is deregistered, wasmx will call special `deregister{}` callback (if present) as a sudo message in the contract. -## Deactivation +### Deactivation A contract can be deactivated automatically if it runs out of gas, or manually by the contract owner. When a contract is deactivated, wasmx will call a special `deactivate{}` callback (if present) as a sudo message in the contract. The contract can be reactivated by the contract owner. -## Fee Grant +### Fee Grant The Wasmx module allows other addresses (contracts, EOAs) to pay for the Begin blocker execution of other contracts through the [`x/feegrant`](https://docs.cosmos.network/main/modules/feegrant) module. When a contract is being registered for the first time, users specify the `FundingMode` which indicates how the contract's execution will be funded. Three modes are supported: -* `SelfFunded` - contract will pay for its own execution (default) -* `GrantOnly` - contract will execute if its associated allowance covers for it (provided by the `GranterAddress` in the `ContractRegistrationRequest`) -* `Dual` - contract will prioritize spending its allowance's funds. In case the allowance cannot cover for execution, it will use its own funds instead +- `SelfFunded` - contract will pay for its own execution (default) +- `GrantOnly` - contract will execute if its associated allowance covers for it (provided by the `GranterAddress` in the `ContractRegistrationRequest`) +- `Dual` - contract will prioritize spending its allowance's funds. In case the allowance cannot cover for execution, it will use its own funds instead Given there are 3 kinds of allowances provided by the `x/feegrant` module (Basic, Periodic and AllowedMsg), the wasmx module supports only Basic and Periodic. Granting an `AllowedMsgAllowance` to a contract is discouraged as any contract attempting to use this kind of allowance will error by default. -## Pausing, params update +### Pausing, params update The owner of a contract has the ability to deactivate or activate the contract at any time without requiring a governance vote. They can also update the parameters for contract execution, such as the gas price or gas limit, at any time. -## Batch methods +### Batch methods For convenience, the Wasmx module provides batch versions of some of the previously mentioned proposals, such as batch registration and deregistration, as well as a batch version of the StoreCodeProposal. These batch versions allow multiple proposals to be processed at the same time, rather than individually. diff --git a/.gitbook/developers-native/injective/wasmx/02_data.mdx b/.gitbook/developers-native/injective/wasmx/02_data.md similarity index 100% rename from .gitbook/developers-native/injective/wasmx/02_data.mdx rename to .gitbook/developers-native/injective/wasmx/02_data.md diff --git a/.gitbook/developers-native/injective/wasmx/03_proposals.mdx b/.gitbook/developers-native/injective/wasmx/03_proposals.md similarity index 100% rename from .gitbook/developers-native/injective/wasmx/03_proposals.mdx rename to .gitbook/developers-native/injective/wasmx/03_proposals.md diff --git a/.gitbook/developers-native/injective/wasmx/04_messages.mdx b/.gitbook/developers-native/injective/wasmx/04_messages.md similarity index 92% rename from .gitbook/developers-native/injective/wasmx/04_messages.mdx rename to .gitbook/developers-native/injective/wasmx/04_messages.md index 37b6128..a1b1699 100644 --- a/.gitbook/developers-native/injective/wasmx/04_messages.mdx +++ b/.gitbook/developers-native/injective/wasmx/04_messages.md @@ -3,11 +3,11 @@ sidebar_position: 4 title: Messages --- -# Messages +## Messages -## MsgUpdateContract +### MsgUpdateContract -Updates registered contract execution params (gas price, limit). Can also define a new admin account.\ +Updates registered contract execution params (gas price, limit). Can also define a new admin account. Can be called only by admin (if defined) or contract itself. ```go @@ -25,7 +25,7 @@ type MsgUpdateContract struct { } ``` -## MsgDeactivateContract +### MsgDeactivateContract Deactivates a registered contract (it will no longer be executed in begin blocker) @@ -38,7 +38,7 @@ type MsgDeactivateContract struct { } ``` -## MsgActivateContract +### MsgActivateContract Reactivates a registered contract (it will be executed in begin blocker from now on again) @@ -51,7 +51,7 @@ type MsgActivateContract struct { } ``` -## MsgExecuteContract +### MsgExecuteContract Invokes a function defined within the smart contract. Function and parameters are encoded in `ExecuteMsg`, which is a JSON message encoded in Base64. @@ -64,7 +64,7 @@ type MsgExecuteContract struct { } ``` -## MsgMigrateContract +### MsgMigrateContract Can be issued by the owner of a migratable smart contract to reset its code ID to another one. `MigrateMsg` is a JSON message encoded in Base64. @@ -77,7 +77,7 @@ type MsgMigrateContract struct { } ``` -## MsgUpdateContractOwner +### MsgUpdateContractOwner Can be issued by the smart contract's owner to transfer ownership. @@ -87,4 +87,4 @@ type MsgUpdateContractOwner struct { NewOwner sdk.AccAddress `json:"new_owner" yaml:"new_owner"` Contract sdk.AccAddress `json:"contract" yaml:"contract"` } -``` +``` \ No newline at end of file diff --git a/.gitbook/developers-native/injective/wasmx/05_params.mdx b/.gitbook/developers-native/injective/wasmx/05_params.md similarity index 100% rename from .gitbook/developers-native/injective/wasmx/05_params.mdx rename to .gitbook/developers-native/injective/wasmx/05_params.md diff --git a/.gitbook/developers-native/injective/wasmx/99_errors.mdx b/.gitbook/developers-native/injective/wasmx/99_errors.md similarity index 100% rename from .gitbook/developers-native/injective/wasmx/99_errors.mdx rename to .gitbook/developers-native/injective/wasmx/99_errors.md diff --git a/.gitbook/developers-native/injective/wasmx.mdx b/.gitbook/developers-native/injective/wasmx/index.md similarity index 67% rename from .gitbook/developers-native/injective/wasmx.mdx rename to .gitbook/developers-native/injective/wasmx/index.md index cf95fcc..7a28095 100644 --- a/.gitbook/developers-native/injective/wasmx.mdx +++ b/.gitbook/developers-native/injective/wasmx/index.md @@ -1,17 +1,17 @@ -# WasmX +# `Wasmx` ## Abstract -The `wasmx` module handles integration of [CosmWasm](https://cosmwasm.com) smart contracts with Injective Chain.\ -Its main function is to provide a method for contracts to be executed in the begin blocker section of each block.\ +The `wasmx` module handles integration of [CosmWasm](https://cosmwasm.com) smart contracts with Injective Chain. +Its main function is to provide a method for contracts to be executed in the begin blocker section of each block. A contract may be automatically deactivated if it runs out of gas but can be reactivated by the contract owner. It also includes helper methods for managing contracts, such as a batch code storage proposal. These functions allow for seamless integration of CosmWasm contracts with the Injective Chain and provide useful tools for managing and maintaining those contracts. ## Contents -1. [Concepts](01_concepts.md) -2. [Data](02_data.md) -3. [State](03_proposals.md) -4. [Messages](04_messages.md) -5. [Params](05_params.md) +1. [Concepts](./01_concepts.md) +2. [Data](./02_data.md) +3. [State](./03_proposals.md) +4. [Messages](./04_messages.md) +5. [Params](./05_params.md) diff --git a/.gitbook/developers-native/query-chain.mdx b/.gitbook/developers-native/query-chain.mdx index 9f822dd..eadbfcf 100644 --- a/.gitbook/developers-native/query-chain.mdx +++ b/.gitbook/developers-native/query-chain.mdx @@ -1,23 +1,25 @@ -# Querying the Chain +--- +title: Querying the Chain +--- ## Topics | Topic | Description | | ------------------------------------ | ---------------------------------------------- | -| [Auction](auction.md) | Querying data from the auction module | -| [Auth](auth.md) | Querying data from the auth module | -| [Bank](bank.md) | Query data from the bank module | -| [Distribution](distribution.md) | Query data related to delegating to validators | -| [Exchange](exchange.md) | Query data from the exchange module | -| [Gov](governance.md) | Query data from the governance module | -| [IBC](ibc.md) | Query data related to IBC | -| [Insurance Fund](insurance-funds.md) | Query data related to insurance funds | -| [Mint](mint.md) | Query data from the mint module | -| [Oracl](oracle.md) | Query data related to the oracle api | -| [Peggy](peggy.md) | Query ethereum data using the peggy api | -| [Permissions](permissions.md) | Query data from the permissions module | -| [Staking](staking.md) | Query data from the staking module | -| [Wasm](wasm.md) | Query data from the wasm module | -| [WasmX](wasmx.md) | Query data from the wasmX module | -| [Tendermint](tendermint.md) | Query data related to the tendermint api | -| [Token Factory](token-factory.md) | Query data from the token factory module | +| [Auction](./query-chain/auction/) | Querying data from the auction module | +| [Auth](./query-chain/auth/) | Querying data from the auth module | +| [Bank](./query-chain/bank/) | Query data from the bank module | +| [Distribution](./query-chain/distribution/) | Query data related to delegating to validators | +| [Exchange](./query-chain/exchange/) | Query data from the exchange module | +| [Gov](./query-chain/governance/) | Query data from the governance module | +| [IBC](./query-chain/ibc/) | Query data related to IBC | +| [Insurance Fund](./query-chain/insurance-funds/) | Query data related to insurance funds | +| [Mint](./query-chain/mint/) | Query data from the mint module | +| [Oracl](./query-chain/oracle/) | Query data related to the oracle api | +| [Peggy](./query-chain/peggy/) | Query ethereum data using the peggy api | +| [Permissions](./query-chain/permissions/) | Query data from the permissions module | +| [Staking](./query-chain/staking/) | Query data from the staking module | +| [Wasm](./query-chain/wasm/) | Query data from the wasm module | +| [WasmX](./query-chain/wasmx/) | Query data from the wasmX module | +| [Tendermint](./query-chain/tendermint/) | Query data related to the tendermint api | +| [Token Factory](./query-chain/token-factory/) | Query data from the token factory module | diff --git a/.gitbook/developers-native/query-chain/auction.mdx b/.gitbook/developers-native/query-chain/auction.mdx index 6296a59..4f767f8 100644 --- a/.gitbook/developers-native/query-chain/auction.mdx +++ b/.gitbook/developers-native/query-chain/auction.mdx @@ -1,4 +1,6 @@ -# Auction +--- +title: Auction +--- Example code snippets to query the auction module on the chain. diff --git a/.gitbook/developers-native/query-chain/auth.mdx b/.gitbook/developers-native/query-chain/auth.mdx index 509366c..a9ba47e 100644 --- a/.gitbook/developers-native/query-chain/auth.mdx +++ b/.gitbook/developers-native/query-chain/auth.mdx @@ -1,4 +1,6 @@ -# Auth +--- +title: Auth +--- Example code snippets to query the auth module on the chain. diff --git a/.gitbook/developers-native/query-chain/bank.mdx b/.gitbook/developers-native/query-chain/bank.mdx index 02e6724..8aac2a5 100644 --- a/.gitbook/developers-native/query-chain/bank.mdx +++ b/.gitbook/developers-native/query-chain/bank.mdx @@ -1,4 +1,6 @@ -# Bank +--- +title: Bank +--- Example code snippets to query the chain for bank module related data. diff --git a/.gitbook/developers-native/query-chain/distribution.mdx b/.gitbook/developers-native/query-chain/distribution.mdx index c743b1c..3a11f9b 100644 --- a/.gitbook/developers-native/query-chain/distribution.mdx +++ b/.gitbook/developers-native/query-chain/distribution.mdx @@ -1,4 +1,6 @@ -# Distribution +--- +title: Distribution +--- Example code snippets to query data related to delegating to validators from the chain. diff --git a/.gitbook/developers-native/query-chain/exchange.mdx b/.gitbook/developers-native/query-chain/exchange.mdx index 0d60833..d79865e 100644 --- a/.gitbook/developers-native/query-chain/exchange.mdx +++ b/.gitbook/developers-native/query-chain/exchange.mdx @@ -1,4 +1,6 @@ -# Exchange +--- +title: Exchange +--- Example code snippets to query the exchange module on the chain. diff --git a/.gitbook/developers-native/query-chain/governance.mdx b/.gitbook/developers-native/query-chain/governance.mdx index 826f78c..40d899f 100644 --- a/.gitbook/developers-native/query-chain/governance.mdx +++ b/.gitbook/developers-native/query-chain/governance.mdx @@ -1,4 +1,6 @@ -# Governance +--- +title: Governance +--- Example code snippets to query the governance module on the chain. diff --git a/.gitbook/developers-native/query-chain/ibc.mdx b/.gitbook/developers-native/query-chain/ibc.mdx index f0cf99d..ac32510 100644 --- a/.gitbook/developers-native/query-chain/ibc.mdx +++ b/.gitbook/developers-native/query-chain/ibc.mdx @@ -1,4 +1,6 @@ -# IBC +--- +title: IBC +--- Example code snippets to query the chain for IBC related data. diff --git a/.gitbook/developers-native/query-chain/insurance-funds.mdx b/.gitbook/developers-native/query-chain/insurance-funds.mdx index 3296545..952397c 100644 --- a/.gitbook/developers-native/query-chain/insurance-funds.mdx +++ b/.gitbook/developers-native/query-chain/insurance-funds.mdx @@ -1,4 +1,6 @@ -# Insurance Funds +--- +title: Insurance Funds +--- Example code snippets to query data related to the insurance fund on chain. diff --git a/.gitbook/developers-native/query-chain/mint.mdx b/.gitbook/developers-native/query-chain/mint.mdx index ca90339..b47e925 100644 --- a/.gitbook/developers-native/query-chain/mint.mdx +++ b/.gitbook/developers-native/query-chain/mint.mdx @@ -1,4 +1,6 @@ -# Mint +--- +title: Mint +--- Example code snippets to query the mint module on the chain. diff --git a/.gitbook/developers-native/query-chain/oracle.mdx b/.gitbook/developers-native/query-chain/oracle.mdx index d89a80b..a24e9f4 100644 --- a/.gitbook/developers-native/query-chain/oracle.mdx +++ b/.gitbook/developers-native/query-chain/oracle.mdx @@ -1,4 +1,6 @@ -# Oracle +--- +title: Oracle +--- Example code snippets to query the chain via the oracle api. diff --git a/.gitbook/developers-native/query-chain/peggy.mdx b/.gitbook/developers-native/query-chain/peggy.mdx index b7bb345..d39d960 100644 --- a/.gitbook/developers-native/query-chain/peggy.mdx +++ b/.gitbook/developers-native/query-chain/peggy.mdx @@ -1,4 +1,6 @@ -# Peggy +--- +title: Peggy +--- Example code snippets to query the chain via the peggy api. diff --git a/.gitbook/developers-native/query-chain/permissions.mdx b/.gitbook/developers-native/query-chain/permissions.mdx index 748e195..db78ecc 100644 --- a/.gitbook/developers-native/query-chain/permissions.mdx +++ b/.gitbook/developers-native/query-chain/permissions.mdx @@ -1,4 +1,6 @@ -# Permissions +--- +title: Permissions +--- Example code snippets to query data related to the permissions module on chain. diff --git a/.gitbook/developers-native/query-chain/staking.mdx b/.gitbook/developers-native/query-chain/staking.mdx index 6837d08..552b4ca 100644 --- a/.gitbook/developers-native/query-chain/staking.mdx +++ b/.gitbook/developers-native/query-chain/staking.mdx @@ -1,4 +1,6 @@ -# Staking +--- +title: Staking +--- Example code snippets to query the chain's staking module diff --git a/.gitbook/developers-native/query-chain/tendermint.mdx b/.gitbook/developers-native/query-chain/tendermint.mdx index 4fd076a..84b2375 100644 --- a/.gitbook/developers-native/query-chain/tendermint.mdx +++ b/.gitbook/developers-native/query-chain/tendermint.mdx @@ -1,4 +1,6 @@ -# Tendermint +--- +title: Tendermint +--- Example code snippets to query for chain node related data. diff --git a/.gitbook/developers-native/query-chain/token-factory.mdx b/.gitbook/developers-native/query-chain/token-factory.mdx index 0bd5079..2ff0a07 100644 --- a/.gitbook/developers-native/query-chain/token-factory.mdx +++ b/.gitbook/developers-native/query-chain/token-factory.mdx @@ -1,4 +1,6 @@ -# Token Factory +--- +title: Token Factory +--- Example code snippets to query the chain for token factory module related data. diff --git a/.gitbook/developers-native/query-chain/wasm.mdx b/.gitbook/developers-native/query-chain/wasm.mdx index c2957e9..8cfdf22 100644 --- a/.gitbook/developers-native/query-chain/wasm.mdx +++ b/.gitbook/developers-native/query-chain/wasm.mdx @@ -1,4 +1,6 @@ -# Wasm +--- +title: Wasm +--- Example code snippets to query the wasm module on chain diff --git a/.gitbook/developers-native/query-chain/wasmx.mdx b/.gitbook/developers-native/query-chain/wasmx.mdx index f6e0329..656aa41 100644 --- a/.gitbook/developers-native/query-chain/wasmx.mdx +++ b/.gitbook/developers-native/query-chain/wasmx.mdx @@ -1,4 +1,6 @@ -# WasmX +--- +title: WasmX +--- Example code snippets to query the wasmX module on chain diff --git a/.gitbook/developers-native/query-ethereum.mdx b/.gitbook/developers-native/query-ethereum.mdx index 6e7f9d9..b18a4f6 100644 --- a/.gitbook/developers-native/query-ethereum.mdx +++ b/.gitbook/developers-native/query-ethereum.mdx @@ -1,4 +1,6 @@ -# Querying Ethereum with GraphQL +--- +title: Querying Ethereum with GraphQL +--- Example code snippets to query data from Ethereum. diff --git a/.gitbook/developers-native/query-indexer-stream.mdx b/.gitbook/developers-native/query-indexer-stream.mdx index caaf5ca..afb8ff9 100644 --- a/.gitbook/developers-native/query-indexer-stream.mdx +++ b/.gitbook/developers-native/query-indexer-stream.mdx @@ -1,4 +1,6 @@ -# Streaming the Indexer +--- +title: Streaming the Indexer +--- ## Topics diff --git a/.gitbook/developers-native/query-indexer-stream/account.mdx b/.gitbook/developers-native/query-indexer-stream/account.mdx index 9ebb3fd..1e934de 100644 --- a/.gitbook/developers-native/query-indexer-stream/account.mdx +++ b/.gitbook/developers-native/query-indexer-stream/account.mdx @@ -1,4 +1,6 @@ -# Account +--- +title: Account +--- Example code snippets to stream from the indexer for subaccount related data. diff --git a/.gitbook/developers-native/query-indexer-stream/auction.mdx b/.gitbook/developers-native/query-indexer-stream/auction.mdx index 4af2151..92eea5b 100644 --- a/.gitbook/developers-native/query-indexer-stream/auction.mdx +++ b/.gitbook/developers-native/query-indexer-stream/auction.mdx @@ -1,4 +1,6 @@ -# Auction +--- +title: Auction +--- Example code snippets to stream from the indexer for auction module related data. diff --git a/.gitbook/developers-native/query-indexer-stream/derivatives.mdx b/.gitbook/developers-native/query-indexer-stream/derivatives.mdx index ba4d400..d679cc6 100644 --- a/.gitbook/developers-native/query-indexer-stream/derivatives.mdx +++ b/.gitbook/developers-native/query-indexer-stream/derivatives.mdx @@ -1,4 +1,6 @@ -# Derivatives +--- +title: Derivatives +--- Example code snippets to query the indexer for derivative module related data. diff --git a/.gitbook/developers-native/query-indexer-stream/explorer.mdx b/.gitbook/developers-native/query-indexer-stream/explorer.mdx index c7d3c25..6d37915 100644 --- a/.gitbook/developers-native/query-indexer-stream/explorer.mdx +++ b/.gitbook/developers-native/query-indexer-stream/explorer.mdx @@ -1,4 +1,6 @@ -# Explorer +--- +title: Explorer +--- Example code snippets to stream from the indexer for explorer module related data. diff --git a/.gitbook/developers-native/query-indexer-stream/oracle.mdx b/.gitbook/developers-native/query-indexer-stream/oracle.mdx index 6de75e3..ff6a636 100644 --- a/.gitbook/developers-native/query-indexer-stream/oracle.mdx +++ b/.gitbook/developers-native/query-indexer-stream/oracle.mdx @@ -1,4 +1,6 @@ -# Oracle +--- +title: Oracle +--- Example code snippets to query the indexer for oracle module related data. diff --git a/.gitbook/developers-native/query-indexer-stream/portfolio.mdx b/.gitbook/developers-native/query-indexer-stream/portfolio.mdx index b285cab..c45ba50 100644 --- a/.gitbook/developers-native/query-indexer-stream/portfolio.mdx +++ b/.gitbook/developers-native/query-indexer-stream/portfolio.mdx @@ -1,4 +1,6 @@ -# Portfolio +--- +title: Portfolio +--- Example code snippets to stream from the indexer for portfolio module related data. diff --git a/.gitbook/developers-native/query-indexer-stream/spot.mdx b/.gitbook/developers-native/query-indexer-stream/spot.mdx index 69c3514..033493b 100644 --- a/.gitbook/developers-native/query-indexer-stream/spot.mdx +++ b/.gitbook/developers-native/query-indexer-stream/spot.mdx @@ -1,4 +1,6 @@ -# Spot +--- +title: Spot +--- Example code snippets to stream from the indexer for spot market module related data. diff --git a/.gitbook/developers-native/query-indexer.mdx b/.gitbook/developers-native/query-indexer.mdx index f914205..ecfde31 100644 --- a/.gitbook/developers-native/query-indexer.mdx +++ b/.gitbook/developers-native/query-indexer.mdx @@ -1,18 +1,20 @@ -# Querying the Indexer +--- +title: Querying the Indexer +--- ## Topics | Topic | Description | | ------------------------------------------------------------- | ------------------------------------------------ | -| [Account](account.md) | Querying data from the account module | -| [Auction](auction.md) | Querying data from the auction module | -| [Derivatives](derivatives.md) | Query data from the derivatives module | -| [Explorer](explorer.md) | Query data related to the explorer module | -| [Leaderboard](leaderboard.md) | Query data related to the leaderboard module | -| [Insurance Fund](insurance-funds.md) | Query data from the insurance fund module | -| [Markets](markets.md) | Query data for both spot and derivatives markets | -| [Mito](mito.md) | Query data from the ninja vaults module | -| [Oracle](oracle.md) | Query data related to the oracle | -| [Portfolio](portfolio.md) | Query data related to the portfolio module | -| [Spot](spot.md) | Query data from the spot module | -| [Transaction](transaction.md) | Query data related to the transaction module | +| [Account](./query-indexer/account/) | Querying data from the account module | +| [Auction](./query-indexer/auction/) | Querying data from the auction module | +| [Derivatives](./query-indexer/derivatives/) | Query data from the derivatives module | +| [Explorer](./query-indexer/explorer/) | Query data related to the explorer module | +| [Leaderboard](./query-indexer/leaderboard/) | Query data related to the leaderboard module | +| [Insurance Fund](./query-indexer/insurance-funds/) | Query data from the insurance fund module | +| [Markets](./query-indexer/markets/) | Query data for both spot and derivatives markets | +| [Mito](./query-indexer/mito/) | Query data from the ninja vaults module | +| [Oracle](./query-indexer/oracle/) | Query data related to the oracle | +| [Portfolio](./query-indexer/portfolio/) | Query data related to the portfolio module | +| [Spot](./query-indexer/spot/) | Query data from the spot module | +| [Transaction](./query-indexer/transaction/) | Query data related to the transaction module | diff --git a/.gitbook/developers-native/query-indexer/account.mdx b/.gitbook/developers-native/query-indexer/account.mdx index b0434b5..9893195 100644 --- a/.gitbook/developers-native/query-indexer/account.mdx +++ b/.gitbook/developers-native/query-indexer/account.mdx @@ -1,4 +1,6 @@ -# Account +--- +title: Account +--- Example code snippets to query the indexer for subaccount related data. @@ -6,7 +8,7 @@ Example code snippets to query the indexer for subaccount related data. ### Fetch user's portfolio details -This includes available balance, unrealized Pnl, and portfolio value. Note: **deprecated** → use [Portfolio](../query-indexer/portfolio.md#using-grpc) instead +This includes available balance, unrealized Pnl, and portfolio value. Note: **deprecated** → use [Portfolio](../query-indexer/portfolio/#using-grpc) instead ```ts import { IndexerGrpcAccountApi } from '@injectivelabs/sdk-ts' diff --git a/.gitbook/developers-native/query-indexer/auction.mdx b/.gitbook/developers-native/query-indexer/auction.mdx index 6fe58fa..4d64c50 100644 --- a/.gitbook/developers-native/query-indexer/auction.mdx +++ b/.gitbook/developers-native/query-indexer/auction.mdx @@ -1,4 +1,6 @@ -# Auction +--- +title: Auction +--- Example code snippets to query the indexer for auction module related data. diff --git a/.gitbook/developers-native/query-indexer/derivatives.mdx b/.gitbook/developers-native/query-indexer/derivatives.mdx index 8096f16..0403663 100644 --- a/.gitbook/developers-native/query-indexer/derivatives.mdx +++ b/.gitbook/developers-native/query-indexer/derivatives.mdx @@ -1,4 +1,6 @@ -# Derivatives +--- +title: Derivatives +--- Example code snippets to query the indexer for derivative module related data. diff --git a/.gitbook/developers-native/query-indexer/explorer.mdx b/.gitbook/developers-native/query-indexer/explorer.mdx index d0ac61f..5011d96 100644 --- a/.gitbook/developers-native/query-indexer/explorer.mdx +++ b/.gitbook/developers-native/query-indexer/explorer.mdx @@ -1,4 +1,6 @@ -# Explorer +--- +title: Explorer +--- Example code snippets to query the indexer for explorer module related data. diff --git a/.gitbook/developers-native/query-indexer/insurance-funds.mdx b/.gitbook/developers-native/query-indexer/insurance-funds.mdx index ce04668..071360e 100644 --- a/.gitbook/developers-native/query-indexer/insurance-funds.mdx +++ b/.gitbook/developers-native/query-indexer/insurance-funds.mdx @@ -1,4 +1,6 @@ -# Insurance Funds +--- +title: Insurance Funds +--- Example code snippets to query the indexer for insurance fund module related data. diff --git a/.gitbook/developers-native/query-indexer/leaderboard.mdx b/.gitbook/developers-native/query-indexer/leaderboard.mdx index 95e2124..3d93604 100644 --- a/.gitbook/developers-native/query-indexer/leaderboard.mdx +++ b/.gitbook/developers-native/query-indexer/leaderboard.mdx @@ -1,4 +1,6 @@ -# Leaderboard +--- +title: Leaderboard +--- Example code snippets to query the indexer for leaderboard module related data. diff --git a/.gitbook/developers-native/query-indexer/markets.mdx b/.gitbook/developers-native/query-indexer/markets.mdx index 74f0ecd..32c4ab9 100644 --- a/.gitbook/developers-native/query-indexer/markets.mdx +++ b/.gitbook/developers-native/query-indexer/markets.mdx @@ -1,4 +1,6 @@ -# Markets +--- +title: Markets +--- Example code snippets to query the indexer for all markets data diff --git a/.gitbook/developers-native/query-indexer/mito.mdx b/.gitbook/developers-native/query-indexer/mito.mdx index 0b297a4..d9b1176 100644 --- a/.gitbook/developers-native/query-indexer/mito.mdx +++ b/.gitbook/developers-native/query-indexer/mito.mdx @@ -1,4 +1,6 @@ -# Mito +--- +title: Mito +--- Example code snippets to query the indexer for the Mito vault module related data. diff --git a/.gitbook/developers-native/query-indexer/oracle.mdx b/.gitbook/developers-native/query-indexer/oracle.mdx index 6fa713d..6f0e349 100644 --- a/.gitbook/developers-native/query-indexer/oracle.mdx +++ b/.gitbook/developers-native/query-indexer/oracle.mdx @@ -1,4 +1,6 @@ -# Oracle +--- +title: Oracle +--- Example code snippets to query the indexer for oracle module related data. diff --git a/.gitbook/developers-native/query-indexer/portfolio.mdx b/.gitbook/developers-native/query-indexer/portfolio.mdx index 07335d5..bb030e2 100644 --- a/.gitbook/developers-native/query-indexer/portfolio.mdx +++ b/.gitbook/developers-native/query-indexer/portfolio.mdx @@ -1,4 +1,6 @@ -# Portfolio +--- +title: Portfolio +--- Example code snippets to query the indexer for portfolio module related data. diff --git a/.gitbook/developers-native/query-indexer/spot.mdx b/.gitbook/developers-native/query-indexer/spot.mdx index 554bdaf..ad2cbea 100644 --- a/.gitbook/developers-native/query-indexer/spot.mdx +++ b/.gitbook/developers-native/query-indexer/spot.mdx @@ -1,4 +1,6 @@ -# Spot +--- +title: Spot +--- Example code snippets to query the indexer for spot market module related data. diff --git a/.gitbook/developers-native/query-indexer/transaction.mdx b/.gitbook/developers-native/query-indexer/transaction.mdx index a8b4b2d..ae6ad52 100644 --- a/.gitbook/developers-native/query-indexer/transaction.mdx +++ b/.gitbook/developers-native/query-indexer/transaction.mdx @@ -1,6 +1,8 @@ -# Web3 Gateway Transactions +--- +title: Web3 Gateway Transactions +--- -Example code snippets to query the indexer for transaction module related data. Used only when interacting with the [Web3Gateway](../transactions/web3-gateway.md) +Example code snippets to query the indexer for transaction module related data. Used only when interacting with the [Web3Gateway](../transactions/web3-gateway/) ## Using gRPC diff --git a/.gitbook/developers-native/transactions.mdx b/.gitbook/developers-native/transactions.mdx index 634c9fc..a91c739 100644 --- a/.gitbook/developers-native/transactions.mdx +++ b/.gitbook/developers-native/transactions.mdx @@ -1,4 +1,6 @@ -# Transactions +--- +title: Transactions +--- _Pre-requisite reading:_ [Cosmos SDK Transactions](https://docs.cosmos.network/main/learn/advanced/transactions) @@ -35,10 +37,10 @@ Every transaction we want to broadcast to Injective has the same flow. The flow | Topic | Description | | ------------------------------------------------- | ---------------------------------------------------------- | -| [Using the Ethereum approach](ethereum.md) | Prepare/Sign EIP712 typed data then broadcast | -| [Using the Cosmos approach](cosmos.md) | Prepare/Sign/Broadcast Cosmos transactions | -| [Using a Private Key](private-key.md) | Prepare/Sign/Broadcast Cosmos transaction with private key | -| [Web3Gateway Microservice](web3-gateway.md) | A microservice for supporting fee Delegation | -| [Msg Broadcaster](msgbroadcaster.md) | Abstraction for broadcasting messages | +| [Using the Ethereum approach](./transactions/ethereum/) | Prepare/Sign EIP712 typed data then broadcast | +| [Using the Cosmos approach](./transactions/cosmos/) | Prepare/Sign/Broadcast Cosmos transactions | +| [Using a Private Key](./transactions/private-key/) | Prepare/Sign/Broadcast Cosmos transaction with private key | +| [Web3Gateway Microservice](./transactions/web3-gateway/) | A microservice for supporting fee Delegation | +| [Msg Broadcaster](./transactions/msgbroadcaster/) | Abstraction for broadcasting messages | **The messages that are available (and examples) can be found in Core Modules section of the Wiki.** diff --git a/.gitbook/developers-native/transactions/cosmos-ledger-keplr.mdx b/.gitbook/developers-native/transactions/cosmos-ledger-keplr.mdx index bb3876e..16d05c0 100644 --- a/.gitbook/developers-native/transactions/cosmos-ledger-keplr.mdx +++ b/.gitbook/developers-native/transactions/cosmos-ledger-keplr.mdx @@ -1,10 +1,12 @@ -# Ledger through Keplr Wallet Transaction +--- +title: Ledger through Keplr Wallet Transaction +--- On this page, we are going to have a look at the implementation for Injective when your users are using a Ledger device through the Keplr wallet. As explained before, Injective uses a different derivation curve from the rest of the Cosmos chains which means that the users have to use the Ethereum app (for now) to interact with Injective. -The easiest way all of the edge cases covered and a full out-of-the-box solution for all of the supported wallets on Injective I suggest you have a look at the [MsgBroadcaster + WalletStrategy ](./msgbroadcaster.md#msgbroadcaster-+-wallet-strategy)abstraction. If you want to do your own implementation, let's go through the code example together. +The easiest way all of the edge cases covered and a full out-of-the-box solution for all of the supported wallets on Injective I suggest you have a look at the [MsgBroadcaster + WalletStrategy ](./msgbroadcaster/#msgbroadcaster-+-wallet-strategy)abstraction. If you want to do your own implementation, let's go through the code example together. ## Overview diff --git a/.gitbook/developers-native/transactions/cosmos.mdx b/.gitbook/developers-native/transactions/cosmos.mdx index a49d294..42c7c2f 100644 --- a/.gitbook/developers-native/transactions/cosmos.mdx +++ b/.gitbook/developers-native/transactions/cosmos.mdx @@ -1,4 +1,6 @@ -# Cosmos Transactions +--- +title: Cosmos Transactions +--- Every transaction on Injective follows the same flow. The flow consists of three steps: preparing, signing and broadcasting the transaction. Let's dive into each step separately and explain the process in-depth (including examples) so we can understand the whole transaction flow. diff --git a/.gitbook/developers-native/transactions/ethereum-ledger.mdx b/.gitbook/developers-native/transactions/ethereum-ledger.mdx index 99646b1..3973703 100644 --- a/.gitbook/developers-native/transactions/ethereum-ledger.mdx +++ b/.gitbook/developers-native/transactions/ethereum-ledger.mdx @@ -1,4 +1,6 @@ -# Ethereum Ledger Transaction +--- +title: Ethereum Ledger Transaction +--- ## Signing Transactions on Injective using Ledger diff --git a/.gitbook/developers-native/transactions/ethereum.mdx b/.gitbook/developers-native/transactions/ethereum.mdx index 84b2085..11b8b88 100644 --- a/.gitbook/developers-native/transactions/ethereum.mdx +++ b/.gitbook/developers-native/transactions/ethereum.mdx @@ -1,4 +1,6 @@ -# Ethereum Transaction +--- +title: Ethereum Transaction +--- Every transaction on Injective follows the same flow. The flow consists of three steps: preparing, signing and broadcasting the transaction. Let's dive into each step separately and explain the process in-depth (including examples) so we can understand the whole transaction flow. diff --git a/.gitbook/developers-native/transactions/msgbroadcaster.mdx b/.gitbook/developers-native/transactions/msgbroadcaster.mdx index f4c87f4..07552d5 100644 --- a/.gitbook/developers-native/transactions/msgbroadcaster.mdx +++ b/.gitbook/developers-native/transactions/msgbroadcaster.mdx @@ -1,8 +1,10 @@ -# MsgBroadcaster Transaction +--- +title: MsgBroadcaster Transaction +--- The `MsgBroadcaster` abstraction class is a way to broadcast transactions on Injective with ease. With it, you can pass a Message that you want to be packed in a transaction and the signer's address and the transaction will be prepared, signed, and broadcasted. -An example of usage can be found on our [Helix demo repo](https://github.com/InjectiveLabs/injective-helix-demo). As for the messages that you can pass to the `broadcast` methods, you can find examples in the [Core Modules](../examples/README.md) section of the docs. +An example of usage can be found on our [Helix demo repo](https://github.com/InjectiveLabs/injective-helix-demo). As for the messages that you can pass to the `broadcast` methods, you can find examples in the [Core Modules](../examples/) section of the docs. ## MsgBroadcaster + Wallet Strategy @@ -99,7 +101,7 @@ export interface MsgBroadcasterTxOptions { ```` -To override the `endpoints` and use your infrastructure (which is something we recommend), please read more on the [Networks](../../developers/concepts/networks.md) page on the endpoints you need to provide and how to set them up. +To override the `endpoints` and use your infrastructure (which is something we recommend), please read more on the [Networks](../../developers/concepts/networks/) page on the endpoints you need to provide and how to set them up. ## MsgBroadcaster with Private Key diff --git a/.gitbook/developers-native/transactions/private-key.mdx b/.gitbook/developers-native/transactions/private-key.mdx index f5ff40c..7d07fc9 100644 --- a/.gitbook/developers-native/transactions/private-key.mdx +++ b/.gitbook/developers-native/transactions/private-key.mdx @@ -1,4 +1,6 @@ -# Private Key Transaction +--- +title: Private Key Transaction +--- In this document, we are going to show you how to use a PrivateKey to sign transactions on Injective. diff --git a/.gitbook/developers-native/transactions/web3-gateway.mdx b/.gitbook/developers-native/transactions/web3-gateway.mdx index ca6d6b4..dcc53f5 100644 --- a/.gitbook/developers-native/transactions/web3-gateway.mdx +++ b/.gitbook/developers-native/transactions/web3-gateway.mdx @@ -1,4 +1,6 @@ -# Web3 Gateway Transaction +--- +title: Web3 Gateway Transaction +--- _Pre-requisite reading #1:_ [Transaction Lifecycle](https://docs.cosmos.network/main/basics/tx-lifecycle) diff --git a/.gitbook/developers-native/wallets.mdx b/.gitbook/developers-native/wallets.mdx index f86ebb1..7d1dff0 100644 --- a/.gitbook/developers-native/wallets.mdx +++ b/.gitbook/developers-native/wallets.mdx @@ -1,4 +1,6 @@ -# Wallets +--- +title: Wallets +--- Injective defines its own custom `Account` type that uses Ethereum's ECDSA secp256k1 curve for keys. In simple words said, it means that Injective's Account is native (compatible) with Ethereum accounts. This allows users to use Ethereum native wallets to interact with Injective. @@ -19,7 +21,7 @@ With the explanation above, we can understand that once you have your **PublicKe | Topic | Description | | ------------------------------------------------------- | --------------------------------------------------------------- | -| [Accounts on Injective](accounts.md) | Accounts/Wallets definition on Injective | -| [Wallet Connections](connections.md) | Connecting directly using Metamask or Keplr | -| [Wallet Strategy](strategy.md) | Using the WalletStrategy to connect using different wallets | -| [Offchain (Arbitrary) Data](offchain-data.md) | Signing and verifying data offchain using the ADR-036 by Cosmos | +| [Accounts on Injective](./wallets/accounts/) | Accounts/Wallets definition on Injective | +| [Wallet Connections](./wallets/connections/) | Connecting directly using Metamask or Keplr | +| [Wallet Strategy](./wallets/strategy/) | Using the WalletStrategy to connect using different wallets | +| [Offchain (Arbitrary) Data](./wallets/offchain-data/) | Signing and verifying data offchain using the ADR-036 by Cosmos | diff --git a/.gitbook/developers-native/wallets/accounts.mdx b/.gitbook/developers-native/wallets/accounts.mdx index 2d95709..dca6c7e 100644 --- a/.gitbook/developers-native/wallets/accounts.mdx +++ b/.gitbook/developers-native/wallets/accounts.mdx @@ -1,4 +1,6 @@ -# Accounts +--- +title: Accounts +--- Injective defines its own custom Account type that uses Ethereum's ECDSA secp256k1 curve for keys. This satisfies the [EIP84](https://github.com/ethereum/EIPs/issues/84) for full [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki) paths. The root HD path for Injective-based accounts is `m/44'/60'/0'/0.` diff --git a/.gitbook/developers-native/wallets/connections.mdx b/.gitbook/developers-native/wallets/connections.mdx index 8539a82..f41263f 100644 --- a/.gitbook/developers-native/wallets/connections.mdx +++ b/.gitbook/developers-native/wallets/connections.mdx @@ -1,12 +1,14 @@ -# Wallet Connections +--- +title: Wallet Connections +--- Injective supports both Ethereum and Cosmos native wallets. You can use popular wallets like Metamask, Ledger, Keplr, Leap, etc. to sign transactions on Injective. ### Wallet Strategy -The recommended way to have support for all of these wallets out of the box is to use the [WalletStrategy](strategy.md) abstraction we've built. This approach will enable your dApp users to connect and interact with different wallets. +The recommended way to have support for all of these wallets out of the box is to use the [WalletStrategy](./strategy/) abstraction we've built. This approach will enable your dApp users to connect and interact with different wallets. -Combining it with the [MsgBroadcaster](../transactions/msgbroadcaster.md) abstraction allows you to sign transactions using one function call. This is what's being used on all products like Helix, Hub, Explorer, etc., and we strongly recommend using this approach in your dApp. +Combining it with the [MsgBroadcaster](../transactions/msgbroadcaster/) abstraction allows you to sign transactions using one function call. This is what's being used on all products like Helix, Hub, Explorer, etc., and we strongly recommend using this approach in your dApp. In case you still want to use some wallet natively (without the WalletStrategy class), we are going to provide examples of how to connect to a dApp built on Injective via Metamask and Keplr in this doc. @@ -37,7 +39,7 @@ console.log(injectiveAddresses) * **Sign transactions using Metamask** -An example of how to prepare + sign + broadcast a transaction on Injective using Metamask can be found [here](../transactions/ethereum.md). +An example of how to prepare + sign + broadcast a transaction on Injective using Metamask can be found [here](../transactions/ethereum/). ### Keplr @@ -68,4 +70,4 @@ const getKeplr = () => { ``` * **Sign transactions using Keplr** -An example of how to prepare + sign + broadcast a transaction on Injective using Keplr can be found in [Cosmos Transactions](../transactions/cosmos.md). +An example of how to prepare + sign + broadcast a transaction on Injective using Keplr can be found in [Cosmos Transactions](../transactions/cosmos/). diff --git a/.gitbook/developers-native/wallets/offchain-data.mdx b/.gitbook/developers-native/wallets/offchain-data.mdx index 128030c..2b79e22 100644 --- a/.gitbook/developers-native/wallets/offchain-data.mdx +++ b/.gitbook/developers-native/wallets/offchain-data.mdx @@ -1,4 +1,6 @@ -# Offchain (Arbitrary) Data +--- +title: Offchain (Arbitrary) Data +--- On this page, we'll provide an example of how to sign and verify arbitrary data as per the [ADR-036](https://docs.cosmos.network/main/build/architecture/adr-036-arbitrary-signature) specification on Cosmos. diff --git a/.gitbook/developers-native/wallets/strategy.mdx b/.gitbook/developers-native/wallets/strategy.mdx index a5ffe91..a37ae48 100644 --- a/.gitbook/developers-native/wallets/strategy.mdx +++ b/.gitbook/developers-native/wallets/strategy.mdx @@ -1,4 +1,6 @@ -# Wallet Strategy +--- +title: Wallet Strategy +--- The main purpose of the `@injectivelabs/wallet-strategy` is to offer developers a way to have different wallet implementations on Injective. All of these wallets implementations are exposing the same `ConcreteStrategy` interface which means that users can just use these methods without the need to know the underlying implementation for specific wallets as they are abstracted away. diff --git a/.gitbook/developers.mdx b/.gitbook/developers.mdx deleted file mode 100644 index f256b86..0000000 --- a/.gitbook/developers.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -description: >- - The goal of this section is to help developers build their projects on - Injective ---- - -# Developers - -Injective is the only blockchain specifically designed for cross-chain trading, derivatives, DeFi, and Web3 applications. Positioned to become the premier global destination for DeFi ecosystem builders, Injective offers a multitude of advantages for developers, empowering them to build more powerful applications in less time. - -## Why Build on Injective? - -
Optimized for DeFi⇾ Specialized modules
⇾ Low-latency infrastructure
⇾ Quicker development
⇾ Greater capabilities
⇾ Unlock new potential
Commercial-Grade Scalability⇾ 25,000+ TPS
⇾ 650ms block times
⇾ Instant finality
⇾ MEV-resistant
⇾ $0.0003 per transaction
Highly Interoperable⇾ Native interoperability, 23+ networks, including Ethereum & Solana
⇾ IBC-Enabled, 110+ chains
Intuitive Developer Experience⇾ Natively integrated execution layer
⇾ WASM + EVM
⇾ Powered by Rust, Golang, and Solidity
- -## What Are You Interested In? - -
EVMBuild smart contracts and dApps on Injective's Ethereum Virtual Machinedevelopers-evmdev-hero.png
CosmwasmBuild smart contracts and dApps on Injective's CosmWasm moduledevelopers-cosmwasmlaunch-token-hero.png
DeFiBuild decentralized finance applications, for example a DEX like Helixdevelopers-defitrader-hero.png
Native ModulesBuild using Injective's native modules. (low-level)developers-nativetxs-hero.png
diff --git a/.gitbook/developers/assets.mdx b/.gitbook/developers/assets.mdx deleted file mode 100644 index 5d1b13d..0000000 --- a/.gitbook/developers/assets.mdx +++ /dev/null @@ -1 +0,0 @@ -# Assets diff --git a/.gitbook/developers/assets/denom.mdx b/.gitbook/developers/assets/denom.mdx index 26b728d..09681e4 100644 --- a/.gitbook/developers/assets/denom.mdx +++ b/.gitbook/developers/assets/denom.mdx @@ -1,4 +1,6 @@ -# Denom +--- +title: Denom +--- A denom is how assets are represented within the Bank module of Injective. These assets can be used for trading, creating new markets on the exchange module, participating in auctions, transferring to another address, etc. @@ -18,5 +20,5 @@ Token is simply a denom on the Injective chain with some meta information. The m **Deprecation Notice** Note that there was a "Denom Client" available within the Injective SDK. -This has been deprecated in favour of [Injective List](./injective-list.md). +This has been deprecated in favour of [Injective List](./injective-list/).
diff --git a/.gitbook/developers/assets/index.mdx b/.gitbook/developers/assets/index.mdx new file mode 100644 index 0000000..65a9b21 --- /dev/null +++ b/.gitbook/developers/assets/index.mdx @@ -0,0 +1,4 @@ +--- +title: Assets +--- + diff --git a/.gitbook/developers/assets/injective-list.mdx b/.gitbook/developers/assets/injective-list.mdx index a65b998..168f367 100644 --- a/.gitbook/developers/assets/injective-list.mdx +++ b/.gitbook/developers/assets/injective-list.mdx @@ -1,4 +1,6 @@ -# Injective List +--- +title: Injective List +--- We have moved the on-chain denoms token metadata to the [injective-list](https://github.com/InjectiveLabs/injective-lists) repository. This repository will aggregate data from several sources and produce a comprehensive token metadata master list. diff --git a/.gitbook/developers/assets/token-create.mdx b/.gitbook/developers/assets/token-create.mdx index 3d704b8..fe4ac80 100644 --- a/.gitbook/developers/assets/token-create.mdx +++ b/.gitbook/developers/assets/token-create.mdx @@ -1,4 +1,6 @@ -# Creating Tokens +--- +title: Creating Tokens +--- The easiest way to create your own token on Injective is by using the `tokenfactory` module. The `tokenfactory` module allows any account to create a new token with the name `factory/{creator address}/{subdenom}`. Because tokens are namespaced by creator address, this allows token minting to be permissionless, due to not needing to resolve name collisions. @@ -16,4 +18,4 @@ One special use case for the factory denoms is the `CW20_ADAPTER`. Using this ad The denom for a CW20 asset is always in the `factory/{CW20_ADAPTER_CONTRACT_ADDRESS}/{CW20_ASSET_ADDRESS}` where `CW20_ADAPTER_CONTRACT_ADDRESS=inj14ejqjyq8um4p3xfqj74yld5waqljf88f9eneuk` for mainnet.
-To start creating your denoms, head to our [TokenFactory Core Module page](../../developers-native/examples/token-factory.md)to see examples. +To start creating your denoms, head to our [TokenFactory Core Module page](../../developers-native/examples/token-factory/)to see examples. diff --git a/.gitbook/developers/assets/token-metadata.mdx b/.gitbook/developers/assets/token-metadata.mdx index 79b35e3..8f0081a 100644 --- a/.gitbook/developers/assets/token-metadata.mdx +++ b/.gitbook/developers/assets/token-metadata.mdx @@ -1,4 +1,6 @@ -# Token Metadata +--- +title: Token Metadata +--- Assets on Injective are represented as denoms. Denoms (and the amounts) are not human readable and this is why we need to have a way to "attach" token metadata information for a particular denom. @@ -17,6 +19,6 @@ We maintain our token metadata list off-chain for faster access to the[ injectiv Verifying your token's metadata can be done in a couple of ways. Here are the verification levels and what they mean: * **Verified** → Your asset metadata has been **submitted and verified** to the `@injectivelabs/token-metadata` package. You can find a tutorial on how to add your token's metadata to the package [here](https://github.com/InjectiveLabs/injective-lists/blob/master/CONTRIBUTING.md). -* **Internal** → Your asset's metadata has been verified on-chain using the `MsgSetDenomMetadata` message, as explained [here](../../developers-native/examples/token-factory.md#msgsetdenommetadata). +* **Internal** → Your asset's metadata has been verified on-chain using the `MsgSetDenomMetadata` message, as explained [here](../../developers-native/examples/token-factory/#msgsetdenommetadata). * **External** → Your asset's metadata has been verified on some external source like from Ethereum's contract details, etc. * **Unverified** → Your asset's metadata has not been provided anywhere. diff --git a/.gitbook/developers/concepts/calculation-min-price-tick-size.mdx b/.gitbook/developers/concepts/calculation-min-price-tick-size.mdx index c72d487..2b0b881 100644 --- a/.gitbook/developers/concepts/calculation-min-price-tick-size.mdx +++ b/.gitbook/developers/concepts/calculation-min-price-tick-size.mdx @@ -1,4 +1,6 @@ -# Market min price tick size calculation +--- +title: Market min price tick size calculation +--- The min market price tick size for an order price - if a market has an minPriceTickSick of `0.001` and order submission with the price of `0.0011` will be rejected. diff --git a/.gitbook/developers/concepts/calculation-min-quantity-tick-size.mdx b/.gitbook/developers/concepts/calculation-min-quantity-tick-size.mdx index d6f4b1c..ad9c430 100644 --- a/.gitbook/developers/concepts/calculation-min-quantity-tick-size.mdx +++ b/.gitbook/developers/concepts/calculation-min-quantity-tick-size.mdx @@ -1,4 +1,6 @@ -# Market min quantity tick size calculation +--- +title: Market min quantity tick size calculation +--- The min market quantity tick size for an order price - if a market has an minQuantityTickSize of `0.001` and order submission with the quantity of `0.0011` will be rejected. diff --git a/.gitbook/developers/concepts/cosmjs-support.mdx b/.gitbook/developers/concepts/cosmjs-support.mdx index 5ad6fa2..098117f 100644 --- a/.gitbook/developers/concepts/cosmjs-support.mdx +++ b/.gitbook/developers/concepts/cosmjs-support.mdx @@ -1,10 +1,12 @@ -# CosmJs Support +--- +title: CosmJs Support +--- Injective is not natively supported on the `@cosmjs` packages. It's highly recommended to use our `@injectivelabs` packages to interact with Injective. If you are familiar with the `@cosmjs` packages we are exporting similar interfaces/classes that work the same as the classes on `@cosmjs` but have support for Injective as well. -Again, keep in mind that the recommended approach is to use the Injective's standard approach, which you can learn more about in [Cosmos transactions](../../developers-native/transactions/cosmos.md). +Again, keep in mind that the recommended approach is to use the Injective's standard approach, which you can learn more about in [Cosmos transactions](../../developers-native/transactions/cosmos/). ## Usage using Keplr @@ -70,7 +72,7 @@ import { assertIsBroadcastTxSuccess } from '@cosmjs/stargate' Here is an example on how to use the `@injectivelabs` alternatives from the `@cosmjs` packages in a node or CLI environment. -Again, keep in mind that the recommended approach is to use the [MsgBroadcasterWithPk](../../developers-native/transactions/private-key.md#example-with-msgbroadcasterwithpk) abstraction to follow the Injective's standard approach. +Again, keep in mind that the recommended approach is to use the [MsgBroadcasterWithPk](../../developers-native/transactions/private-key/#example-with-msgbroadcasterwithpk) abstraction to follow the Injective's standard approach. ```ts import { diff --git a/.gitbook/developers/concepts/grpc-protobuf.mdx b/.gitbook/developers/concepts/grpc-protobuf.mdx index a85beaa..7903bc4 100644 --- a/.gitbook/developers/concepts/grpc-protobuf.mdx +++ b/.gitbook/developers/concepts/grpc-protobuf.mdx @@ -1,4 +1,6 @@ -# gRPC & Protobuf +--- +title: gRPC & Protobuf +--- gRPC is a modern open-source high-performance Remote Procedure Call (RPC) framework that can run in any environment. It can efficiently connect services in and across data centers with pluggable support for load balancing, tracing, health checking, and authentication. It is also applicable in the last mile of distributed computing to connect devices, mobile applications, and browsers to backend services. diff --git a/.gitbook/developers/concepts.mdx b/.gitbook/developers/concepts/index.mdx similarity index 89% rename from .gitbook/developers/concepts.mdx rename to .gitbook/developers/concepts/index.mdx index f8a60fa..c0139d5 100644 --- a/.gitbook/developers/concepts.mdx +++ b/.gitbook/developers/concepts/index.mdx @@ -1,3 +1,5 @@ -# Technical Concepts +--- +title: Technical Concepts +--- Learning these concepts can help you be a more efficient dApps developer on top of Injective. We'll keep the explanations brief so only the necessary context is shared with the reader. We encourage developers to explore these concepts more thoroughly at their own convenience. diff --git a/.gitbook/developers/concepts/indexer-api.mdx b/.gitbook/developers/concepts/indexer-api.mdx index 8bc6b27..d655d21 100644 --- a/.gitbook/developers/concepts/indexer-api.mdx +++ b/.gitbook/developers/concepts/indexer-api.mdx @@ -1,4 +1,6 @@ -# Indexer API +--- +title: Indexer API +--- The Indexer API is a collection of microservices that serve data indexed from the Injective chain. The Injective Chain emits events when a transaction is included and there is an event listener within the Indexer API that listens for these events, processes them, and stores the data in a MongoDB. Querying the chain directly is an expensive (and less performant) API call than querying an API serving data from a MongoDB which is why the Indexer API exists. diff --git a/.gitbook/developers/concepts/networks.mdx b/.gitbook/developers/concepts/networks.mdx index d15d187..f16e779 100644 --- a/.gitbook/developers/concepts/networks.mdx +++ b/.gitbook/developers/concepts/networks.mdx @@ -1,4 +1,6 @@ -# Networks +--- +title: Networks +--- Up-to-date public Endpoints can be found [here](https://docs.injective.network/develop/public-endpoints/#mainnet). We **do not recommend** using them in production for applications having high usage/traffic. There are thousands of developers using the public infrastructure and we cannot promise 100% uptime and reliability. \ diff --git a/.gitbook/developers/concepts/sentry-node.mdx b/.gitbook/developers/concepts/sentry-node.mdx index 2c03c88..64416d9 100644 --- a/.gitbook/developers/concepts/sentry-node.mdx +++ b/.gitbook/developers/concepts/sentry-node.mdx @@ -1,4 +1,6 @@ -# Sentry Node +--- +title: Sentry Node +--- Sentry node is a read-only full node running the Injective chain. A full node is a server running a chain's binary (its software) that fully validates transactions and blocks of a blockchain and keeps a full record of all historic activity. A full node is distinct from a pruned node that processes only block headers and a small subset of transactions. Running a full node requires more resources than a pruned node. Validators can decide to run either a full node or a pruned node, but they need to make sure they retain enough blocks to be able to validate new blocks. diff --git a/.gitbook/developers/concepts/token-factory.mdx b/.gitbook/developers/concepts/token-factory.mdx index 4d0649b..cf644e0 100644 --- a/.gitbook/developers/concepts/token-factory.mdx +++ b/.gitbook/developers/concepts/token-factory.mdx @@ -1,4 +1,6 @@ -# Token Factory +--- +title: Token Factory +--- The Token Factory module on Injective which allows users and contracts to create new native tokens and swap native tokens with CW20 tokens using the Mint + Burn model. This is an important feature to have on chain because representing assets from different sources to a native bank denom is crucial to allow users to access the rest of the on-chain modules like exchange, auction, insurance funds, etc. The token factory denoms are in the following format `factory/{creator address}/{subdenom}`. diff --git a/.gitbook/developers/concepts/trading-account.mdx b/.gitbook/developers/concepts/trading-account.mdx index e10f8e7..cea0e73 100644 --- a/.gitbook/developers/concepts/trading-account.mdx +++ b/.gitbook/developers/concepts/trading-account.mdx @@ -1,4 +1,6 @@ -# Trading Account +--- +title: Trading Account +--- Subaccounts or Trading Accounts are a concept that allows you to decouple the funds in the native Injective Bank module (which can be used for staking, bidding on auctions, participating in governance, creating markets, etc) into an isolated trading account from which you can execute trades. One Injective address can have an unlimited number of trading accounts. The way they are represented is `${ethereumAddress}${subaccountNonce}` where the `ethereumAddress` is the `hex` version of the `bech32` Injective address and the `subaccountNonce` is the nonce represented in 12 bytes. An example trading account at nonce 1 would be `0xc7dca7c15c364865f77a4fb67ab11dc95502e6fe000000000000000000000001`. diff --git a/.gitbook/developers/convert-addresses.mdx b/.gitbook/developers/convert-addresses.mdx index 6650b00..142e776 100644 --- a/.gitbook/developers/convert-addresses.mdx +++ b/.gitbook/developers/convert-addresses.mdx @@ -1,10 +1,12 @@ -# Convert addresses +--- +title: Convert addresses +--- Within this document, we'll outline some examples on how to convert addresses between different formats and derivation paths. ### Convert Hex ↔ Bech32 address -As we've mentioned in the [wallet](../defi/wallet/README.md "mention") section, Injective addresses are compatible with Ethereum addresses. You can convert between the two formats easily. +As we've mentioned in the [wallet](../defi/walle/ t) section, Injective addresses are compatible with Ethereum addresses. You can convert between the two formats easily. ### Using TypeScript @@ -55,5 +57,5 @@ config(); ``` -More examples can be found in [wallet accounts](../defi/wallet/accounts.md). +More examples can be found in [wallet accounts](../defi/wallet/accounts/). diff --git a/.gitbook/developers/dapps/configure-nuxt.mdx b/.gitbook/developers/dapps/configure-nuxt.mdx index 4ab3913..df20d26 100644 --- a/.gitbook/developers/dapps/configure-nuxt.mdx +++ b/.gitbook/developers/dapps/configure-nuxt.mdx @@ -1,4 +1,6 @@ -# Configuring Nuxt +--- +title: Configuring Nuxt +--- ## Nuxt3 - The Intuitive Web Framework diff --git a/.gitbook/developers/dapps/configure-react.mdx b/.gitbook/developers/dapps/configure-react.mdx index d447d2b..86f22ac 100644 --- a/.gitbook/developers/dapps/configure-react.mdx +++ b/.gitbook/developers/dapps/configure-react.mdx @@ -1,4 +1,6 @@ -# Configuring React +--- +title: Configuring React +--- ## React - Library for building user interfaces diff --git a/.gitbook/developers/dapps/example-dex.mdx b/.gitbook/developers/dapps/example-dex.mdx index 9409106..d582124 100644 --- a/.gitbook/developers/dapps/example-dex.mdx +++ b/.gitbook/developers/dapps/example-dex.mdx @@ -1,4 +1,6 @@ -# DEX +--- +title: DEX +--- Within these short series we are going to showcase how easy it is to build a DEX on top of Injective. There is an open-sourced [DEX](https://github.com/InjectiveLabs/injective-dex) which everyone can reference and use to build on top of Injective. For those who want to start from scratch, this is the right place to start. diff --git a/.gitbook/developers/dapps/example-smart-contract.mdx b/.gitbook/developers/dapps/example-smart-contract.mdx index 13b30b6..fa66f1a 100644 --- a/.gitbook/developers/dapps/example-smart-contract.mdx +++ b/.gitbook/developers/dapps/example-smart-contract.mdx @@ -1,4 +1,6 @@ -# Smart Contract +--- +title: Smart Contract +--- Within these short series we are going to showcase how easy it is to build a dApp on top of Injective. There is an open-sourced [dApp](https://github.com/InjectiveLabs/injective-simple-sc-counter-ui) which everyone can reference and use to build on top of Injective. There are examples for Next, Nuxt and Vanilla Js. For those who want to start from scratch, this is the right place to start. diff --git a/.gitbook/developers/dapps/example-webpack.mdx b/.gitbook/developers/dapps/example-webpack.mdx index 591aff2..965b6da 100644 --- a/.gitbook/developers/dapps/example-webpack.mdx +++ b/.gitbook/developers/dapps/example-webpack.mdx @@ -1,6 +1,8 @@ -# Simple HTML example with Webpack +--- +title: Simple HTML example with Webpack +--- -The [example](https://github.com/InjectiveLabs/injective-ts-webpack-example) is based on the [Cosmos transaction handling section](../../developers-native/transactions/cosmos.md). +The [example](https://github.com/InjectiveLabs/injective-ts-webpack-example) is based on the [Cosmos transaction handling section](../../developers-native/transactions/cosmos/). ## Running the example diff --git a/.gitbook/developers/dapps.mdx b/.gitbook/developers/dapps/index.mdx similarity index 88% rename from .gitbook/developers/dapps.mdx rename to .gitbook/developers/dapps/index.mdx index 95e0c12..38e44f1 100644 --- a/.gitbook/developers/dapps.mdx +++ b/.gitbook/developers/dapps/index.mdx @@ -1,4 +1,6 @@ -# Building dApps +--- +title: Building dApps +--- Injective is a Layer-1 blockchain built for finance. Injective offers developers out-of-the-box primitives for building decentralized financial applications in addition to an open and permissionless smart contracts layer providing advanced capabilities in building robust Web3 applications. @@ -22,7 +24,7 @@ The latest versions are published using the `next` tag. For stable versions use If you are looking for how to build a dApp on Injective EVM, -you should check out the guides in [your first EVM dApp](../../developers-evm/dapps/README.md). +you should check out the guides in [your first EVM dApp](../../developers-evm/dapps/). ### Create Injective dApp CLI tool @@ -37,18 +39,17 @@ $ npx @injectivelabs/create-injective-app | Topic | Description | | ----------------------------------------- | --------------------------- | -| [Configuring Nuxt](configure-nuxt.md) | Configuring Nuxt 3.x + Vite | -| [Configuring React](configure-react.md) | Configuring React 18 + Vite | +| [Configuring Nuxt](./configure-nuxt/) | Configuring Nuxt 3.x + Vite | +| [Configuring React](./configure-react/) | Configuring React 18 + Vite | ### dApps | Topic | Description | | ------------------------------------------ | -------------------------------------------------------- | -| [DEX](example-dex.md) | Building a decentralized exchange on top of Injective | -| [Simple Smart Contract](example-smart-contract.md) | Building a simple smart contract app on top of Injective | -| [Webpack](example-webpack.md) | Simple HTML example with Webpack and Injective | +| [DEX](./example-dex/) | Building a decentralized exchange on top of Injective | +| [Simple Smart Contract](./example-smart-contract/) | Building a simple smart contract app on top of Injective | +| [Webpack](./example-webpack/) | Simple HTML example with Webpack and Injective | {/* -| [Bridge](example-bridge.md) | Building a simple bridge between Injective and Ethereum | +| [Bridge](./example-bridge/) | Building a simple bridge between Injective and Ethereum | */} - diff --git a/.gitbook/developers/dapps/run-examples.mdx b/.gitbook/developers/dapps/run-examples.mdx index 46770f7..cf04e95 100644 --- a/.gitbook/developers/dapps/run-examples.mdx +++ b/.gitbook/developers/dapps/run-examples.mdx @@ -1,9 +1,8 @@ --- description: Each of these examples can be run in a simple TypeScript environment. +title: Running examples --- -# Running examples - You can clone this open-sourced repository [https://github.com/InjectiveLabs/injective-ts-examples](https://github.com/InjectiveLabs/injective-ts-examples) and follow the steps in **📚 Getting Started** to get started with your examples! You can check the examples in the repository to make everything work out of the box in a Node environment, querying and sending a transaction. diff --git a/.gitbook/developers/index.mdx b/.gitbook/developers/index.mdx new file mode 100644 index 0000000..7951d92 --- /dev/null +++ b/.gitbook/developers/index.mdx @@ -0,0 +1,93 @@ +--- +description: >- + The goal of this section is to help developers build their projects on + Injective +title: Developers +--- + +Injective is the only blockchain specifically designed for cross-chain trading, derivatives, DeFi, and Web3 applications. Positioned to become the premier global destination for DeFi ecosystem builders, Injective offers a multitude of advantages for developers, empowering them to build more powerful applications in less time. + +## Why Build on Injective? + + + + ⇾ Specialized modules
+ ⇾ Low-latency infrastructure
+ ⇾ Quicker development
+ ⇾ Greater capabilities
+ ⇾ Unlock new potential +
+ + ⇾ 25,000+ TPS
+ ⇾ 650ms block times
+ ⇾ Instant finality
+ ⇾ MEV-resistant
+ ⇾ $0.0003 per transaction +
+ + ⇾ Native interoperability, 23+ networks, including Ethereum & Solana
+ ⇾ IBC-Enabled, 110+ chains +
+ + ⇾ Natively integrated execution layer
+ ⇾ WASM + EVM
+ ⇾ Powered by Rust, Golang, and Solidity +
+
+ +## What Are You Interested In? + + + + Build smart contracts and dApps on Injective's Ethereum Virtual Machine + + + Build smart contracts and dApps on Injective's CosmWasm module + + + Build decentralized finance applications, for example a DEX like Helix + + + Build using Injective's native modules. (low-level) + + diff --git a/.gitbook/developers/injectived.mdx b/.gitbook/developers/injectived.mdx deleted file mode 100644 index ad4d6ee..0000000 --- a/.gitbook/developers/injectived.mdx +++ /dev/null @@ -1,8 +0,0 @@ -# injectived - -`injectived` is the command-line interface and node daemon that connects to Injective. Injective core is the official Golang reference implementation of the Injective node software. - -## Getting Started - -
InstallLearn how to install injectivedBroken linkcode-hero.png
UsageLearn how to use injectivedBroken linkdev-hero.png
CommandsLearn advanced commands for injectivedBroken linktxs-hero.png
- diff --git a/.gitbook/developers/injectived/advanced.mdx b/.gitbook/developers/injectived/advanced.mdx index bc34e97..269cae9 100644 --- a/.gitbook/developers/injectived/advanced.mdx +++ b/.gitbook/developers/injectived/advanced.mdx @@ -1,4 +1,6 @@ -# Commands +--- +title: Commands +--- This section describes the commands available from `injectived`, the command line interface that connects a running `injectived` process (node). @@ -26,7 +28,7 @@ injectived add-genesis-account acc1 100000000000inj ### `collect-gentxs` -Collects genesis transactions and outputs them to `genesis.json`. For more information on `genesis.json`, see the Join Testnet or Join Mainnet guide [here](../../infra/join-a-network.md). +Collects genesis transactions and outputs them to `genesis.json`. For more information on `genesis.json`, see the Join Testnet or Join Mainnet guide [here](../../infra/join-a-network/). **Syntax** diff --git a/.gitbook/developers/injectived/index.mdx b/.gitbook/developers/injectived/index.mdx new file mode 100644 index 0000000..232833d --- /dev/null +++ b/.gitbook/developers/injectived/index.mdx @@ -0,0 +1,37 @@ +--- +title: injectived +--- + +`injectived` is the command-line interface and node daemon that connects to Injective. Injective core is the official Golang reference implementation of the Injective node software. + +## Getting Started + + + + Learn how to install injectived + + + Learn how to use injectived + + + Learn advanced commands for injectived + + diff --git a/.gitbook/developers/injectived/install.mdx b/.gitbook/developers/injectived/install.mdx index 78d3457..d866be0 100644 --- a/.gitbook/developers/injectived/install.mdx +++ b/.gitbook/developers/injectived/install.mdx @@ -1,4 +1,6 @@ -# Install injectived +--- +title: Install injectived +--- ## Platform compatibiltiy guide @@ -45,7 +47,7 @@ Version v1.14.1 (0fe59376dc) Compiled at 20250302-2204 using Go go1.23.1 (amd64) ``` -Continue to [Using injectived](./use.md) to learn how to use `injectived` CLI for interacting with the Injective blockchain. +Continue to [Using injectived](./use/) to learn how to use `injectived` CLI for interacting with the Injective blockchain. ## Getting started with Docker @@ -61,7 +63,7 @@ Compiled at 20250302-2220 using Go go1.22.11 (amd64) This is compatible with most platforms and arm64 / x86_64 architectures. -Continue to [Using injectived](./use.md) to learn how to use `injectived` CLI for interacting with the Injective blockchain. +Continue to [Using injectived](./use/) to learn how to use `injectived` CLI for interacting with the Injective blockchain. ## Getting started with source code @@ -85,4 +87,4 @@ Compiled at 20250302-2230 using Go go1.24.0 (amd64) (the commit hash may be different, as the open-source repository is published separately from the pre-built versions). -Continue to [Using injectived](./use.md) to learn how to use `injectived` CLI for interacting with the Injective blockchain. +Continue to [Using injectived](./use/) to learn how to use `injectived` CLI for interacting with the Injective blockchain. diff --git a/.gitbook/developers/injectived/use.mdx b/.gitbook/developers/injectived/use.mdx index a725010..01014cc 100644 --- a/.gitbook/developers/injectived/use.mdx +++ b/.gitbook/developers/injectived/use.mdx @@ -1,4 +1,6 @@ -# Using injectived +--- +title: Using injectived +--- The following page explains what one can do via `injectived`, the command-line interface that connects to Injective. You can use `injectived` to interact with the Injective blockchain by uploading smart contracts, querying data, managing staking activities, working with governance proposals, and more. @@ -6,7 +8,7 @@ The following page explains what one can do via `injectived`, the command-line i ### Ensuring injectived is installed -See [Install injectived](./install.md) for more information. If you have installed `injectived` successfully, you should be able to run the following command: +See [Install injectived](./install/) for more information. If you have installed `injectived` successfully, you should be able to run the following command: ```bash injectived version @@ -55,7 +57,7 @@ Before you can access the Injective blockchain, you need to have a node running. To query the state and send transactions, you must connect to a node, which is the access point to the entire network of peer connections. You can either run your own full node or connect to someone else’s. -[Running own node](../../infra/join-a-network.md) is for advanced users only. For most users, it is recommended to connect to a public node. +[Running own node](../../infra/join-a-network/) is for advanced users only. For most users, it is recommended to connect to a public node. To set the RPC endpoint, you can use the following command: diff --git a/.gitbook/developers/modules/injective/erc20/README.md b/.gitbook/developers/modules/injective/erc20/README.md index 1e39d52..3fddc0b 100644 --- a/.gitbook/developers/modules/injective/erc20/README.md +++ b/.gitbook/developers/modules/injective/erc20/README.md @@ -7,7 +7,7 @@ The erc20 module allows for the associations of existing bank denoms with ERC-20 ## Contents -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** +1. **[Concepts](./01_concepts/)** +2. **[State](./02_state/)** +3. **[Messages](./03_messages/)** +4. **[Events](./04_events/)** diff --git a/.gitbook/developers/modules/injective/permissions/04_launch_permissioned_asset.md b/.gitbook/developers/modules/injective/permissions/04_launch_permissioned_asset.md index 57a7555..c64ac93 100644 --- a/.gitbook/developers/modules/injective/permissions/04_launch_permissioned_asset.md +++ b/.gitbook/developers/modules/injective/permissions/04_launch_permissioned_asset.md @@ -5,7 +5,7 @@ title: How to Launch Permissioned Assets # How to Launch Permissioned Assets -Permissioned assets can be launched using [Injective APIs/SDKs](https://api.injective.exchange/#permissions) or the Injective CLI, `injectived`. See [injectived](../../../../developers/injectived/README.md) for more information on using the Injective CLI. +Permissioned assets can be launched using [Injective APIs/SDKs](https://api.injective.exchange/#permissions) or the Injective CLI, `injectived`. See [injectived](https://docs.injective.network/developers/injectived) for more information on using the Injective CLI. ```bash injectived tx permissions [command] diff --git a/.gitbook/developers/network-information.mdx b/.gitbook/developers/network-information.mdx index e381164..108009a 100644 --- a/.gitbook/developers/network-information.mdx +++ b/.gitbook/developers/network-information.mdx @@ -1,9 +1,8 @@ --- description: Essential information about the Injective network +title: Network Information --- -# Network Information - ## Injective Testnet Details * Chain ID: `injective-888` @@ -14,7 +13,7 @@ Note that the Injective Chain ID for EVM is `1439`. However, it natively uses a chain ID of `injective-888`. While the chain IDs are different, they map to the **same** network. -See [EVM network information](../developers-evm/network-information.md) for more details. +See [EVM network information](../developers-evm/network-information/) for more details.
## Injective Devnet Details @@ -32,5 +31,5 @@ Note that the Injective Chain ID for EVM is `1776`. However, it natively uses a chain ID of `injective-1`. While the chain IDs are different, they map to the **same** network. -See [EVM network information](../developers-evm/network-information.md) for more details. +See [EVM network information](../developers-evm/network-information/) for more details.
diff --git a/.gitbook/developers/testnet-proposals.mdx b/.gitbook/developers/testnet-proposals.mdx index fbb9a32..174ae01 100644 --- a/.gitbook/developers/testnet-proposals.mdx +++ b/.gitbook/developers/testnet-proposals.mdx @@ -1,4 +1,6 @@ -# Testnet Proposals +--- +title: Testnet Proposals +--- Let's say that you want to submit a proposal on `testnet`. Because there is a short period of voting time for the proposals, we recommend lowering the deposit on the proposal to not make the proposal go into voting stage directly. Basically, it should be slightly less than `min_deposit` value. diff --git a/.gitbook/docs.json b/.gitbook/docs.json index cd37e25..dd55adf 100644 --- a/.gitbook/docs.json +++ b/.gitbook/docs.json @@ -16,7 +16,7 @@ "group": "Start here", "expanded": true, "pages": [ - "README" + "index" ] }, { @@ -24,11 +24,11 @@ "expanded": false, "icon": "coins", "pages": [ - "defi", + "defi/index", { "group": "Wallet", "pages": [ - "defi/wallet", + "defi/wallet/index", "defi/wallet/create", "defi/wallet/accounts" ] @@ -36,7 +36,7 @@ { "group": "Trading", "pages": [ - "defi/trading", + "defi/trading/index", "defi/trading/order-types", "defi/trading/fees", "defi/trading/margin", @@ -55,7 +55,7 @@ { "group": "Token Standards", "pages": [ - "defi/tokens", + "defi/tokens/index", "defi/tokens/inj-coin", "defi/tokens/token-factory", "defi/tokens/cw20-standard" @@ -79,7 +79,7 @@ { "group": "Open Liquidity Program", "pages": [ - "defi/open-liquidity-program", + "defi/open-liquidity-program/index", "defi/open-liquidity-program/introduction", "defi/open-liquidity-program/rewards", "defi/open-liquidity-program/epochs", @@ -106,7 +106,7 @@ "expanded": false, "icon": "network-wired", "pages": [ - "infra", + "infra/index", "infra/interact-node-command-line", "infra/interact-node-grpc", "infra/interact-node-go", @@ -119,7 +119,7 @@ { "group": "Mainnet Validator", "pages": [ - "infra/validator-mainnet", + "infra/validator-mainnet/index", "infra/validator-mainnet/peggo", "infra/validator-mainnet/canonical-chain-upgrade", "infra/validator-mainnet/canonical-chain-upgrade-1.16.4", @@ -151,7 +151,7 @@ { "group": "Testnet Validator", "pages": [ - "infra/validator-testnet", + "infra/validator-testnet/index", "infra/validator-testnet/peggo" ] }, @@ -166,13 +166,13 @@ "expanded": false, "icon": "laptop-code", "pages": [ - "developers", + "developers/index", "developers/convert-addresses", "developers/network-information", { "group": "injectived", "pages": [ - "developers/injectived", + "developers/injectived/index", "developers/injectived/install", "developers/injectived/use", "developers/injectived/advanced", @@ -182,7 +182,7 @@ { "group": "Concepts", "pages": [ - "developers/concepts", + "developers/concepts/index", "developers/concepts/sentry-node", "developers/concepts/indexer-api", "developers/concepts/trading-account", @@ -197,7 +197,7 @@ { "group": "Assets", "pages": [ - "developers/assets", + "developers/assets/index", "developers/assets/denom", "developers/assets/token-metadata", "developers/assets/injective-list", @@ -207,7 +207,7 @@ { "group": "dApps", "pages": [ - "developers/dapps", + "developers/dapps/index", "developers/dapps/configure-nuxt", "developers/dapps/configure-react", "developers/dapps/run-examples", @@ -231,12 +231,12 @@ "expanded": false, "icon": "rectangle-code", "pages": [ - "developers-evm", + "developers-evm/index", "developers-evm/network-information", { "group": "Your First EVM Smart Contract", "pages": [ - "developers-evm/smart-contracts", + "developers-evm/smart-contracts/index", "developers-evm/smart-contracts/compile-hardhat", "developers-evm/smart-contracts/test-hardhat", "developers-evm/smart-contracts/deploy-hardhat", @@ -252,7 +252,7 @@ { "group": "Your First EVM dApp", "pages": [ - "developers-evm/dapps", + "developers-evm/dapps/index", "developers-evm/dapps/connect-with-metamask", "developers-evm/dapps/connect-with-walletconnect" ] @@ -273,11 +273,11 @@ "expanded": false, "icon": "comet", "pages": [ - "developers-cosmwasm", + "developers-cosmwasm/index", { "group": "CosmWasm Smart Contracts", "pages": [ - "developers-cosmwasm/smart-contracts", + "developers-cosmwasm/smart-contracts/index", "developers-cosmwasm/smart-contracts/your-first-smart-contract", "developers-cosmwasm/smart-contracts/injective-name-service", "developers-cosmwasm/smart-contracts/neptune-service", @@ -299,7 +299,7 @@ "expanded": false, "icon": "money-bill-transfer", "pages": [ - "developers-defi", + "developers-defi/index", "developers-defi/calculate-min-price-tick-size", "developers-defi/min-quantity-tick-size", "developers-defi/testnet-faucet-integration", @@ -315,11 +315,11 @@ "expanded": false, "icon": "microchip", "pages": [ - "developers-native", + "developers-native/index", { "group": "Wallets", "pages": [ - "developers-native/wallets", + "developers-native/wallets/index", "developers-native/wallets/accounts", "developers-native/wallets/connections", "developers-native/wallets/strategy", @@ -329,14 +329,14 @@ { "group": "Bridges", "pages": [ - "developers-native/bridges", + "developers-native/bridges/index", "developers-native/bridges/ethereum" ] }, { "group": "Transactions", "pages": [ - "developers-native/transactions", + "developers-native/transactions/index", "developers-native/transactions/cosmos", "developers-native/transactions/cosmos-ledger-keplr", "developers-native/transactions/ethereum", @@ -349,7 +349,7 @@ { "group": "Transaction Examples", "pages": [ - "developers-native/examples", + "developers-native/examples/index", "developers-native/examples/auction", "developers-native/examples/authz", "developers-native/examples/bank", @@ -369,7 +369,7 @@ { "group": "Querying the Chain", "pages": [ - "developers-native/query-chain", + "developers-native/query-chain/index", "developers-native/query-chain/auction", "developers-native/query-chain/auth", "developers-native/query-chain/bank", @@ -392,7 +392,7 @@ { "group": "Querying the Indexer", "pages": [ - "developers-native/query-indexer", + "developers-native/query-indexer/index", "developers-native/query-indexer/account", "developers-native/query-indexer/auction", "developers-native/query-indexer/derivatives", @@ -410,7 +410,7 @@ { "group": "Streaming the Indexer", "pages": [ - "developers-native/query-indexer-stream", + "developers-native/query-indexer-stream/index", "developers-native/query-indexer-stream/account", "developers-native/query-indexer-stream/auction", "developers-native/query-indexer-stream/derivatives", @@ -424,11 +424,11 @@ { "group": "Injective Modules", "pages": [ - "developers-native/injective", + "developers-native/injective/index", { "group": "Auction", "pages": [ - "developers-native/injective/auction", + "developers-native/injective/auction/index", "developers-native/injective/auction/01_state", "developers-native/injective/auction/02_messages", "developers-native/injective/auction/03_end_block", @@ -440,7 +440,7 @@ { "group": "Exchange", "pages": [ - "developers-native/injective/exchange", + "developers-native/injective/exchange/index", "developers-native/injective/exchange/00_derivative_market_concepts", "developers-native/injective/exchange/01_spot_market_concepts", "developers-native/injective/exchange/02_binary_options_markets", @@ -460,7 +460,7 @@ { "group": "ERC20", "pages": [ - "developers-native/injective/erc20", + "developers-native/injective/erc20/index", "developers-native/injective/erc20/01_concepts", "developers-native/injective/erc20/02_state", "developers-native/injective/erc20/03_messages", @@ -470,7 +470,7 @@ { "group": "EVM", "pages": [ - "developers-native/injective/evm", + "developers-native/injective/evm/index", "developers-native/injective/evm/01_concepts", "developers-native/injective/evm/02_state", "developers-native/injective/evm/03_state_transitions", @@ -485,7 +485,7 @@ { "group": "Insurance", "pages": [ - "developers-native/injective/insurance", + "developers-native/injective/insurance/index", "developers-native/injective/insurance/01_state", "developers-native/injective/insurance/02_state_transitions", "developers-native/injective/insurance/03_messages", @@ -499,7 +499,7 @@ { "group": "OCR", "pages": [ - "developers-native/injective/ocr", + "developers-native/injective/ocr/index", "developers-native/injective/ocr/01_concepts", "developers-native/injective/ocr/02_state", "developers-native/injective/ocr/03_messages", @@ -514,7 +514,7 @@ { "group": "Oracle", "pages": [ - "developers-native/injective/oracle", + "developers-native/injective/oracle/index", "developers-native/injective/oracle/01_state", "developers-native/injective/oracle/02_keeper", "developers-native/injective/oracle/03_messages", @@ -527,7 +527,7 @@ { "group": "Peggy", "pages": [ - "developers-native/injective/peggy", + "developers-native/injective/peggy/index", "developers-native/injective/peggy/01_definitions", "developers-native/injective/peggy/02_workflow", "developers-native/injective/peggy/03_state", @@ -544,7 +544,7 @@ { "group": "Permissions", "pages": [ - "developers-native/injective/permissions", + "developers-native/injective/permissions/index", "developers-native/injective/permissions/01_concepts", "developers-native/injective/permissions/02_state", "developers-native/injective/permissions/03_state_transitions", @@ -554,7 +554,7 @@ { "group": "TokenFactory", "pages": [ - "developers-native/injective/tokenfactory", + "developers-native/injective/tokenfactory/index", "developers-native/injective/tokenfactory/01_concepts", "developers-native/injective/tokenfactory/02_state", "developers-native/injective/tokenfactory/03_messages", @@ -566,7 +566,7 @@ { "group": "WasmX", "pages": [ - "developers-native/injective/wasmx", + "developers-native/injective/wasmx/index", "developers-native/injective/wasmx/01_concepts", "developers-native/injective/wasmx/02_data", "developers-native/injective/wasmx/03_proposals", @@ -582,7 +582,7 @@ { "group": "Core Modules", "pages": [ - "developers-native/core", + "developers-native/core/index", "developers-native/core/auth", "developers-native/core/authz", "developers-native/core/bank", diff --git a/.gitbook/faq.mdx b/.gitbook/faq.mdx index cb53f15..d55571c 100644 --- a/.gitbook/faq.mdx +++ b/.gitbook/faq.mdx @@ -1,4 +1,6 @@ -# Injective FAQ +--- +title: Injective FAQ +--- ## Fundamentals diff --git a/.gitbook/glossary.mdx b/.gitbook/glossary.mdx index 84d9d53..0b2e867 100644 --- a/.gitbook/glossary.mdx +++ b/.gitbook/glossary.mdx @@ -2,10 +2,9 @@ description: >- Pocket size cheat sheet for Injective. Use this glossary to learn about terms specific to Injective. +title: Glossary --- -# Glossary - ### Active set The validators that participate in consensus and receive rewards. diff --git a/.gitbook/.gitbook/assets/0_YiPfP8pxHtcyVuWy (1).png b/.gitbook/img/0_YiPfP8pxHtcyVuWy (1).png similarity index 100% rename from .gitbook/.gitbook/assets/0_YiPfP8pxHtcyVuWy (1).png rename to .gitbook/img/0_YiPfP8pxHtcyVuWy (1).png diff --git a/.gitbook/.gitbook/assets/0_YiPfP8pxHtcyVuWy (2).png b/.gitbook/img/0_YiPfP8pxHtcyVuWy (2).png similarity index 100% rename from .gitbook/.gitbook/assets/0_YiPfP8pxHtcyVuWy (2).png rename to .gitbook/img/0_YiPfP8pxHtcyVuWy (2).png diff --git a/.gitbook/.gitbook/assets/0_YiPfP8pxHtcyVuWy.png b/.gitbook/img/0_YiPfP8pxHtcyVuWy.png similarity index 100% rename from .gitbook/.gitbook/assets/0_YiPfP8pxHtcyVuWy.png rename to .gitbook/img/0_YiPfP8pxHtcyVuWy.png diff --git a/.gitbook/.gitbook/assets/6614b644f965e11764db3535_leap.svg b/.gitbook/img/6614b644f965e11764db3535_leap.svg similarity index 100% rename from .gitbook/.gitbook/assets/6614b644f965e11764db3535_leap.svg rename to .gitbook/img/6614b644f965e11764db3535_leap.svg diff --git a/.gitbook/.gitbook/assets/Docs - Add and Bridge ERC20.png b/.gitbook/img/Docs - Add and Bridge ERC20.png similarity index 100% rename from .gitbook/.gitbook/assets/Docs - Add and Bridge ERC20.png rename to .gitbook/img/Docs - Add and Bridge ERC20.png diff --git a/.gitbook/.gitbook/assets/Docs - Deposit From.png b/.gitbook/img/Docs - Deposit From.png similarity index 100% rename from .gitbook/.gitbook/assets/Docs - Deposit From.png rename to .gitbook/img/Docs - Deposit From.png diff --git a/.gitbook/.gitbook/assets/Docs - Deposit Peggy.png b/.gitbook/img/Docs - Deposit Peggy.png similarity index 100% rename from .gitbook/.gitbook/assets/Docs - Deposit Peggy.png rename to .gitbook/img/Docs - Deposit Peggy.png diff --git a/.gitbook/.gitbook/assets/Docs - New Proposal.png b/.gitbook/img/Docs - New Proposal.png similarity index 100% rename from .gitbook/.gitbook/assets/Docs - New Proposal.png rename to .gitbook/img/Docs - New Proposal.png diff --git a/.gitbook/.gitbook/assets/Docs - Quote Denom.png b/.gitbook/img/Docs - Quote Denom.png similarity index 100% rename from .gitbook/.gitbook/assets/Docs - Quote Denom.png rename to .gitbook/img/Docs - Quote Denom.png diff --git a/.gitbook/.gitbook/assets/Docs - Select Ticker.png b/.gitbook/img/Docs - Select Ticker.png similarity index 100% rename from .gitbook/.gitbook/assets/Docs - Select Ticker.png rename to .gitbook/img/Docs - Select Ticker.png diff --git a/.gitbook/.gitbook/assets/Docs - Transaction Submitted.png b/.gitbook/img/Docs - Transaction Submitted.png similarity index 100% rename from .gitbook/.gitbook/assets/Docs - Transaction Submitted.png rename to .gitbook/img/Docs - Transaction Submitted.png diff --git a/.gitbook/.gitbook/assets/Keplr_logo_ver.1.3_2 Light.png b/.gitbook/img/Keplr_logo_ver.1.3_2 Light.png similarity index 100% rename from .gitbook/.gitbook/assets/Keplr_logo_ver.1.3_2 Light.png rename to .gitbook/img/Keplr_logo_ver.1.3_2 Light.png diff --git a/.gitbook/.gitbook/assets/LEDGER-WORDMARK-BLACK-CMYK.png b/.gitbook/img/LEDGER-WORDMARK-BLACK-CMYK.png similarity index 100% rename from .gitbook/.gitbook/assets/LEDGER-WORDMARK-BLACK-CMYK.png rename to .gitbook/img/LEDGER-WORDMARK-BLACK-CMYK.png diff --git a/.gitbook/.gitbook/assets/LEDGER-WORDMARK-BLACK-RGB.svg b/.gitbook/img/LEDGER-WORDMARK-BLACK-RGB.svg similarity index 100% rename from .gitbook/.gitbook/assets/LEDGER-WORDMARK-BLACK-RGB.svg rename to .gitbook/img/LEDGER-WORDMARK-BLACK-RGB.svg diff --git a/.gitbook/.gitbook/assets/LEDGER-WORDMARK-SINGLE-CHARACTER-BLACK-CMYK-01.svg b/.gitbook/img/LEDGER-WORDMARK-SINGLE-CHARACTER-BLACK-CMYK-01.svg similarity index 100% rename from .gitbook/.gitbook/assets/LEDGER-WORDMARK-SINGLE-CHARACTER-BLACK-CMYK-01.svg rename to .gitbook/img/LEDGER-WORDMARK-SINGLE-CHARACTER-BLACK-CMYK-01.svg diff --git a/.gitbook/.gitbook/assets/Logo _ Dark.svg b/.gitbook/img/Logo _ Dark.svg similarity index 100% rename from .gitbook/.gitbook/assets/Logo _ Dark.svg rename to .gitbook/img/Logo _ Dark.svg diff --git a/.gitbook/.gitbook/assets/NINJI-LOGO_NINJI-FULL-WHITECOLOUR.svg b/.gitbook/img/NINJI-LOGO_NINJI-FULL-WHITECOLOUR.svg similarity index 100% rename from .gitbook/.gitbook/assets/NINJI-LOGO_NINJI-FULL-WHITECOLOUR.svg rename to .gitbook/img/NINJI-LOGO_NINJI-FULL-WHITECOLOUR.svg diff --git a/.gitbook/.gitbook/assets/OKX-250x141.png b/.gitbook/img/OKX-250x141.png similarity index 100% rename from .gitbook/.gitbook/assets/OKX-250x141.png rename to .gitbook/img/OKX-250x141.png diff --git a/.gitbook/.gitbook/assets/SVG_MetaMask_Horizontal_White.svg b/.gitbook/img/SVG_MetaMask_Horizontal_White.svg similarity index 100% rename from .gitbook/.gitbook/assets/SVG_MetaMask_Horizontal_White.svg rename to .gitbook/img/SVG_MetaMask_Horizontal_White.svg diff --git a/.gitbook/.gitbook/assets/SVG_MetaMask_Icon_Color.svg b/.gitbook/img/SVG_MetaMask_Icon_Color.svg similarity index 100% rename from .gitbook/.gitbook/assets/SVG_MetaMask_Icon_Color.svg rename to .gitbook/img/SVG_MetaMask_Icon_Color.svg diff --git a/.gitbook/.gitbook/assets/SendToCosmos.png b/.gitbook/img/SendToCosmos.png similarity index 100% rename from .gitbook/.gitbook/assets/SendToCosmos.png rename to .gitbook/img/SendToCosmos.png diff --git a/.gitbook/.gitbook/assets/SendToEth.png b/.gitbook/img/SendToEth.png similarity index 100% rename from .gitbook/.gitbook/assets/SendToEth.png rename to .gitbook/img/SendToEth.png diff --git a/.gitbook/.gitbook/assets/White -Ledger logo.svg b/.gitbook/img/White -Ledger logo.svg similarity index 100% rename from .gitbook/.gitbook/assets/White -Ledger logo.svg rename to .gitbook/img/White -Ledger logo.svg diff --git a/.gitbook/.gitbook/assets/bitget wallet.svg b/.gitbook/img/bitget wallet.svg similarity index 100% rename from .gitbook/.gitbook/assets/bitget wallet.svg rename to .gitbook/img/bitget wallet.svg diff --git a/.gitbook/.gitbook/assets/blog-hero.png b/.gitbook/img/blog-hero.png similarity index 100% rename from .gitbook/.gitbook/assets/blog-hero.png rename to .gitbook/img/blog-hero.png diff --git a/.gitbook/.gitbook/assets/bridge-hero.png b/.gitbook/img/bridge-hero.png similarity index 100% rename from .gitbook/.gitbook/assets/bridge-hero.png rename to .gitbook/img/bridge-hero.png diff --git a/.gitbook/.gitbook/assets/code-hero.png b/.gitbook/img/code-hero.png similarity index 100% rename from .gitbook/.gitbook/assets/code-hero.png rename to .gitbook/img/code-hero.png diff --git a/.gitbook/.gitbook/assets/cosmostation-logo-01.png b/.gitbook/img/cosmostation-logo-01.png similarity index 100% rename from .gitbook/.gitbook/assets/cosmostation-logo-01.png rename to .gitbook/img/cosmostation-logo-01.png diff --git a/.gitbook/.gitbook/assets/dev-hero.png b/.gitbook/img/dev-hero.png similarity index 100% rename from .gitbook/.gitbook/assets/dev-hero.png rename to .gitbook/img/dev-hero.png diff --git a/.gitbook/.gitbook/assets/explorer-hero.png b/.gitbook/img/explorer-hero.png similarity index 100% rename from .gitbook/.gitbook/assets/explorer-hero.png rename to .gitbook/img/explorer-hero.png diff --git a/.gitbook/.gitbook/assets/icons8-speed-32.png b/.gitbook/img/icons8-speed-32.png similarity index 100% rename from .gitbook/.gitbook/assets/icons8-speed-32.png rename to .gitbook/img/icons8-speed-32.png diff --git a/.gitbook/.gitbook/assets/image.png b/.gitbook/img/image.png similarity index 100% rename from .gitbook/.gitbook/assets/image.png rename to .gitbook/img/image.png diff --git a/.gitbook/.gitbook/assets/img.png b/.gitbook/img/img.png similarity index 100% rename from .gitbook/.gitbook/assets/img.png rename to .gitbook/img/img.png diff --git a/.gitbook/.gitbook/assets/inj-hero.png b/.gitbook/img/inj-hero.png similarity index 100% rename from .gitbook/.gitbook/assets/inj-hero.png rename to .gitbook/img/inj-hero.png diff --git a/.gitbook/.gitbook/assets/inj-hub-staking-validators-section.png b/.gitbook/img/inj-hub-staking-validators-section.png similarity index 100% rename from .gitbook/.gitbook/assets/inj-hub-staking-validators-section.png rename to .gitbook/img/inj-hub-staking-validators-section.png diff --git a/.gitbook/.gitbook/assets/launch-market-hero.png b/.gitbook/img/launch-market-hero.png similarity index 100% rename from .gitbook/.gitbook/assets/launch-market-hero.png rename to .gitbook/img/launch-market-hero.png diff --git a/.gitbook/.gitbook/assets/launch-token-hero.png b/.gitbook/img/launch-token-hero.png similarity index 100% rename from .gitbook/.gitbook/assets/launch-token-hero.png rename to .gitbook/img/launch-token-hero.png diff --git a/.gitbook/.gitbook/assets/ledgerr.png b/.gitbook/img/ledgerr.png similarity index 100% rename from .gitbook/.gitbook/assets/ledgerr.png rename to .gitbook/img/ledgerr.png diff --git a/.gitbook/.gitbook/assets/ltp2-2cf6d9420ceec3e5a88fd4de94f6229b.png b/.gitbook/img/ltp2-2cf6d9420ceec3e5a88fd4de94f6229b.png similarity index 100% rename from .gitbook/.gitbook/assets/ltp2-2cf6d9420ceec3e5a88fd4de94f6229b.png rename to .gitbook/img/ltp2-2cf6d9420ceec3e5a88fd4de94f6229b.png diff --git a/.gitbook/.gitbook/assets/multivm-token-single-token-representation-architecture.png b/.gitbook/img/multivm-token-single-token-representation-architecture.png similarity index 100% rename from .gitbook/.gitbook/assets/multivm-token-single-token-representation-architecture.png rename to .gitbook/img/multivm-token-single-token-representation-architecture.png diff --git a/.gitbook/.gitbook/assets/start-hero.png b/.gitbook/img/start-hero.png similarity index 100% rename from .gitbook/.gitbook/assets/start-hero.png rename to .gitbook/img/start-hero.png diff --git a/.gitbook/.gitbook/assets/token-hero.png b/.gitbook/img/token-hero.png similarity index 100% rename from .gitbook/.gitbook/assets/token-hero.png rename to .gitbook/img/token-hero.png diff --git a/.gitbook/.gitbook/assets/torus-logo-blue-3.svg b/.gitbook/img/torus-logo-blue-3.svg similarity index 100% rename from .gitbook/.gitbook/assets/torus-logo-blue-3.svg rename to .gitbook/img/torus-logo-blue-3.svg diff --git a/.gitbook/.gitbook/assets/trader-hero.png b/.gitbook/img/trader-hero.png similarity index 100% rename from .gitbook/.gitbook/assets/trader-hero.png rename to .gitbook/img/trader-hero.png diff --git a/.gitbook/.gitbook/assets/trezor-main-logo-white-rgb.svg b/.gitbook/img/trezor-main-logo-white-rgb.svg similarity index 100% rename from .gitbook/.gitbook/assets/trezor-main-logo-white-rgb.svg rename to .gitbook/img/trezor-main-logo-white-rgb.svg diff --git a/.gitbook/.gitbook/assets/txs-hero.png b/.gitbook/img/txs-hero.png similarity index 100% rename from .gitbook/.gitbook/assets/txs-hero.png rename to .gitbook/img/txs-hero.png diff --git a/.gitbook/.gitbook/assets/user-hero.png b/.gitbook/img/user-hero.png similarity index 100% rename from .gitbook/.gitbook/assets/user-hero.png rename to .gitbook/img/user-hero.png diff --git a/.gitbook/.gitbook/assets/validator-hero.png b/.gitbook/img/validator-hero.png similarity index 100% rename from .gitbook/.gitbook/assets/validator-hero.png rename to .gitbook/img/validator-hero.png diff --git a/.gitbook/.gitbook/assets/valsetupdate.png b/.gitbook/img/valsetupdate.png similarity index 100% rename from .gitbook/.gitbook/assets/valsetupdate.png rename to .gitbook/img/valsetupdate.png diff --git a/.gitbook/.gitbook/assets/wallet-hero-2.png b/.gitbook/img/wallet-hero-2.png similarity index 100% rename from .gitbook/.gitbook/assets/wallet-hero-2.png rename to .gitbook/img/wallet-hero-2.png diff --git a/.gitbook/.gitbook/assets/wallet-hero.png b/.gitbook/img/wallet-hero.png similarity index 100% rename from .gitbook/.gitbook/assets/wallet-hero.png rename to .gitbook/img/wallet-hero.png diff --git a/.gitbook/index.mdx b/.gitbook/index.mdx new file mode 100644 index 0000000..ff670eb --- /dev/null +++ b/.gitbook/index.mdx @@ -0,0 +1,108 @@ +--- +description: >- + Injective is a high-performance, interoperable layer-one blockchain for + building premier Web3 financial applications. +title: About Injective +--- + +## What is Injective? + +Injective is the blockchain built for finance. + +It is the only blockchain where developers can use pre-built, customizable [modules](./developers-native/) to create dynamic applications that aren't possible on other networks. Combined with optimizations to its core architecture and enhanced cross-chain interoperability, Injective offers a high-performance network, ready to efficiently and securely bring the global financial system on-chain. + +---- + + + + Learn how to create a wallet + + + Learn how to start trading on Injective + + + Learn how to run sentry and validator nodes + + + Learn how to build on Injective + + + Join the Injective Discord +
+ Join the Developer Telegram +
+
+ +# Getting Started + +Welcome to your journey of exploring Injective! Before asking questions, please try using the search functionality in the docs. Our goal is to make the documentation self-sufficient, ensuring that onboarding is smooth and everyone can easily learn more about Injective. + +## Quickstart Guide to Injective + + + + + Learn how to create a wallet on Injective and see the supported wallets on Injective + + + Learn about different Token Standards on Injective + + + Learn how to prepare, sign and submit transactions on Injective + + + +## Need Help? + +Should you have some questions or feedback, you can reach out to Discord or Telegram: + +* Join the [Injective Discord server](https://discord.gg/injective) and find the relevant channel. +* Join the [Injective Developer Telegram channel](https://t.me/+8Y_0HOFLhnRlZDU9). diff --git a/.gitbook/infra/archival-setup.mdx b/.gitbook/infra/archival-setup.mdx index 2ec8f51..e19556e 100644 --- a/.gitbook/infra/archival-setup.mdx +++ b/.gitbook/infra/archival-setup.mdx @@ -1,4 +1,6 @@ -# Archival setup +--- +title: Archival setup +--- This guide will walk you through the process of creating a fleet of nodes that serve archival data and how to stitch them together using a gateway diff --git a/.gitbook/infra/cosmovisor.mdx b/.gitbook/infra/cosmovisor.mdx index 8031ccd..9bbe8eb 100644 --- a/.gitbook/infra/cosmovisor.mdx +++ b/.gitbook/infra/cosmovisor.mdx @@ -1,4 +1,6 @@ -# Cosmovisor Setup Guide for the Injective Network +--- +title: Cosmovisor Setup Guide for the Injective Network +--- Cosmovisor is a process manager designed for Cosmos SDK–based blockchains that simplifies the management of binary (chain) upgrades. This guide provides step‐by‐step instructions to set up Cosmovisor for your Injective Network node. diff --git a/.gitbook/infra.mdx b/.gitbook/infra/index.mdx similarity index 86% rename from .gitbook/infra.mdx rename to .gitbook/infra/index.mdx index 011a95e..2d4a586 100644 --- a/.gitbook/infra.mdx +++ b/.gitbook/infra/index.mdx @@ -2,7 +2,6 @@ description: >- This section helps node operators and validators to run, upgrade and maintain their sentry/validator nodes. +title: Infrastructure --- -# Infrastructure - diff --git a/.gitbook/infra/interact-node-command-line.mdx b/.gitbook/infra/interact-node-command-line.mdx index fc5d29d..bbd0afe 100644 --- a/.gitbook/infra/interact-node-command-line.mdx +++ b/.gitbook/infra/interact-node-command-line.mdx @@ -2,4 +2,4 @@ You can use the `injectived` CLI to interact with a node. If you are interacting with a node in your local private network, make sure the node is running in the terminal before you use the CLI. -For more details on how to use `injectived`, see [using injectived](../developers/injectived/use.md "mention"). +For more details on how to use `injectived`, see [using injectived](../developers/injectived/use/ "mention"). diff --git a/.gitbook/infra/interact-node-go.mdx b/.gitbook/infra/interact-node-go.mdx index 629a6c0..a80e9af 100644 --- a/.gitbook/infra/interact-node-go.mdx +++ b/.gitbook/infra/interact-node-go.mdx @@ -1,9 +1,11 @@ -# Interact with a node programmatically with Go +--- +title: Interact with a node programmatically with Go +--- The following examples are in Go, but the Python and TS SDKs can also be used to programatically interact with a node/Injective. -* [TypeScript Examples](../developers-native/examples/README.md) +* [TypeScript Examples](../developers-native/examples/) * [Python Examples](https://github.com/InjectiveLabs/sdk-python/tree/master/examples) @@ -84,4 +86,3 @@ func queryState() error { return nil } ``` - diff --git a/.gitbook/infra/interact-node-grpc.mdx b/.gitbook/infra/interact-node-grpc.mdx index fc0df37..6bd476b 100644 --- a/.gitbook/infra/interact-node-grpc.mdx +++ b/.gitbook/infra/interact-node-grpc.mdx @@ -1,4 +1,6 @@ -# Interact with a node using gRPC +--- +title: Interact with a node using gRPC +--- The Protobuf ecosystem developed tools for different use cases, including code-generation from `*.proto` files into various languages. These tools allow clients to be built easily. Often, the client connection (i.e. the transport) can be plugged and replaced easily. Let's explore a popular transport method, gRPC. @@ -57,4 +59,4 @@ Assuming the state at that block has not yet been pruned by the node, this query Sending transactions using gRPC and REST requires some additional steps: generating the transaction, signing it, and finally broadcasting it. -You can learn more in [transactions](../defi/transactions.md "mention"). +You can learn more in [transactions](../defi/transactions/ "mention"). diff --git a/.gitbook/infra/interact-node-rest.mdx b/.gitbook/infra/interact-node-rest.mdx index 5e0f1b2..d17c75b 100644 --- a/.gitbook/infra/interact-node-rest.mdx +++ b/.gitbook/infra/interact-node-rest.mdx @@ -1,4 +1,6 @@ -# Interact with a node using REST Endpoints +--- +title: Interact with a node using REST Endpoints +--- All gRPC services on the Cosmos SDK are made available for more convenient REST-based queries through gRPC-gateway. The format of the URL path is based on the Protobuf service method's full-qualified name, but may contain small customizations so that final URLs look more idiomatic. For example, the REST endpoint for the `cosmos.bank.v1beta1.Query/AllBalances` method is `GET /cosmos/bank/v1beta1/balances/{address}`. Request arguments are passed as query parameters. @@ -39,4 +41,4 @@ Assuming the state at that block has not yet been pruned by the node, this query Sending transactions using gRPC and REST requires some additional steps: generating the transaction, signing it, and finally broadcasting it. -You can learn more in [transactions](../defi/transactions.md "mention"). +You can learn more in [transactions](../defi/transactions/ "mention"). diff --git a/.gitbook/infra/join-a-network.mdx b/.gitbook/infra/join-a-network.mdx index fff719c..ffe5927 100644 --- a/.gitbook/infra/join-a-network.mdx +++ b/.gitbook/infra/join-a-network.mdx @@ -1,4 +1,6 @@ -# Join a network +--- +title: Join a network +--- This guide will walk you through the process of setting up a standalone network locally, as well as running a node on Mainnet or Testnet. diff --git a/.gitbook/infra/premium-endpoints.mdx b/.gitbook/infra/premium-endpoints.mdx index 955f31a..8018e8f 100644 --- a/.gitbook/infra/premium-endpoints.mdx +++ b/.gitbook/infra/premium-endpoints.mdx @@ -1,11 +1,10 @@ --- description: >- - As a developer, you may be interested in having a dedicated node or - indexing solutions powering your dApp. + As a developer, you may be interested in having a dedicated node or indexing + solutions powering your dApp. +title: Premium Endpoints --- -# Premium Endpoints - Here is a list of external providers offering private Injective infrastructure services. For more information, click on their websites below: * [QuickNode](https://www.quicknode.com/chains/inj) diff --git a/.gitbook/infra/public-endpoints.mdx b/.gitbook/infra/public-endpoints.mdx index b04befe..e1d1771 100644 --- a/.gitbook/infra/public-endpoints.mdx +++ b/.gitbook/infra/public-endpoints.mdx @@ -1,4 +1,6 @@ -# Public Endpoints +--- +title: Public Endpoints +--- We **do not recommend** using these in production for applications having high usage/traffic. There are thousands of developers using the public infrastructure and we cannot promise 100% uptime and reliability. diff --git a/.gitbook/infra/run-node.mdx b/.gitbook/infra/run-node.mdx index 9e41856..0ed6b57 100644 --- a/.gitbook/infra/run-node.mdx +++ b/.gitbook/infra/run-node.mdx @@ -1,4 +1,6 @@ -# Running a node +--- +title: Running a node +--- It is highly recommended that you set up a local private network before joining a public network. This will help you get familiar with the setup process and provide an environment for testing. @@ -23,4 +25,32 @@ Once the node is up and running, there are a few ways to interact with a node, n ## Guides on Running Your Node -
Setup KeyringLearn how to setup your keyringset-up-keyringuser-hero.png
Join a NetworkLearn how to join a networkjoin-a-network.mdbridge-hero.png
Upgrade your nodeLearn how to upgrade your nodeupgrade-nodevalidator-hero.png
+ + + Learn how to setup your keyring + + + Learn how to join a network + + + Learn how to upgrade your node + + diff --git a/.gitbook/infra/set-up-keyring.mdx b/.gitbook/infra/set-up-keyring.mdx index 486884c..40870a9 100644 --- a/.gitbook/infra/set-up-keyring.mdx +++ b/.gitbook/infra/set-up-keyring.mdx @@ -1,7 +1,9 @@ -# Setting up the keyring +--- +title: Setting up the keyring +--- -This document describes how to configure and use the keyring and its various backends for an Injective node. `injectived` should be installed prior to setting up the keyring. See the [Install `injectived` page](../developers/injectived/install.md) for more information. +This document describes how to configure and use the keyring and its various backends for an Injective node. `injectived` should be installed prior to setting up the keyring. See the [Install `injectived` page](../developers/injectived/install/) for more information. The keyring holds the private/public keypairs used to interact with the node. For instance, a validator key needs to be set up before running the Injective node, so that blocks can be correctly signed. The private key can be stored in different locations, called "backends", such as a file or the operating system's own key storage. diff --git a/.gitbook/infra/upgrade-node.mdx b/.gitbook/infra/upgrade-node.mdx index 64a2772..ea12669 100644 --- a/.gitbook/infra/upgrade-node.mdx +++ b/.gitbook/infra/upgrade-node.mdx @@ -1,4 +1,6 @@ -# Upgrade your node +--- +title: Upgrade your node +--- ### Chain Upgrades @@ -17,10 +19,10 @@ To summarize, follow these steps to upgrade your node: ### Upgrading with Cosmovisor -To manage chain upgrades, use [Cosmovisor](./cosmovisor.md). +To manage chain upgrades, use [Cosmovisor](./cosmovisor/). ### Node Maintenance (Managing Storage) As Injective state grows, your disk space may fill up. It’s recommended you periodically prune the chain data by downloading new snapshots. Beyond the overhead on the disk, the node is more performant when the chain state is smaller. -Injective validators take daily light snapshots that you can use to clean the chain state, which grows at about 10-15 GB daily. These snapshots are normally only around 2-3 GB. We recommend pruning the chain data every 300-400 GB. For links to snapshots as well as directions for applying the snapshot/syncing the node, see [Join Mainnet](./join-a-network.md). +Injective validators take daily light snapshots that you can use to clean the chain state, which grows at about 10-15 GB daily. These snapshots are normally only around 2-3 GB. We recommend pruning the chain data every 300-400 GB. For links to snapshots as well as directions for applying the snapshot/syncing the node, see [Join Mainnet](./join-a-network/). diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.13.0.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.13.0.mdx index ea8454f..329c1de 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.13.0.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.13.0.mdx @@ -1,9 +1,8 @@ --- sidebar_position: 16 +title: Upgrade to v1.13.0 --- -# Upgrade to v1.13.0 - Thursday, August 1st, 2024 Following [proposal 420](https://injhub.com/proposals/420/) This indicates that the upgrade procedure should be performed on block number **80319200** diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.13.2.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.13.2.mdx index dea3d32..d01065a 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.13.2.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.13.2.mdx @@ -1,9 +1,8 @@ --- sidebar_position: 17 +title: Upgrade to v1.13.2 --- -# Upgrade to v1.13.2 - Tuesday, August 20th, 2024 Following [proposal 424](https://injhub.com/proposal/424/) This indicates that the upgrade procedure should be performed on block number **82830000** diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.13.3.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.13.3.mdx index d62147f..bf2013c 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.13.3.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.13.3.mdx @@ -1,9 +1,8 @@ --- sidebar_position: 18 +title: Upgrade to v1.13.3 --- -# Upgrade to v1.13.3 - Thursday, Dec 19th, 2024 * [Summary](#summary) diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.14.0.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.14.0.mdx index 6ea13b3..6dc9100 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.14.0.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.14.0.mdx @@ -1,9 +1,8 @@ --- sidebar_position: 19 +title: Upgrade to v1.14.0 --- -# Upgrade to v1.14.0 - Monday, February 17th, 2025 Following [Proposal 494](https://injhub.com/proposals/494/) This indicates that the upgrade procedure should be performed on block number **106315000** diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.14.1.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.14.1.mdx index b2beaea..5c2703f 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.14.1.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.14.1.mdx @@ -1,9 +1,8 @@ --- sidebar_position: 20 +title: Upgrade to v1.14.1 --- -# Upgrade to v1.14.1 - Tuesday, March 4th, 2025 Following [Proposal 500](https://injhub.com/proposals/500) This indicates that the upgrade procedure should be performed on block number **108175000** diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.15.0.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.15.0.mdx index ed92b4b..02ebebe 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.15.0.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.15.0.mdx @@ -1,9 +1,8 @@ --- sidebar_position: 21 +title: Upgrade to v1.15.0 --- -# Upgrade to v1.15.0 - Tuesday, April 22th, 2025 Following [Proposal 518](https://injhub.com/proposals/518) This indicates that the upgrade procedure should be performed on block number **114590000** diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.16.0.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.16.0.mdx index 5479661..9db5f76 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.16.0.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.16.0.mdx @@ -1,4 +1,6 @@ -# Upgrade to v1.16.0 +--- +title: Upgrade to v1.16.0 +--- Thursday, July 31st, 2025 diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.16.1.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.16.1.mdx index 304c8a5..0e935bc 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.16.1.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.16.1.mdx @@ -1,4 +1,6 @@ -# Upgrade to v1.16.1 +--- +title: Upgrade to v1.16.1 +--- Monday, August 4th, 2025 diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.16.2.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.16.2.mdx index 815c5b5..8c44810 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.16.2.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.16.2.mdx @@ -1,4 +1,6 @@ -# Upgrade to v1.16.2 +--- +title: Upgrade to v1.16.2 +--- Tuesday, August 19th, 2025 diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.16.4.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.16.4.mdx index 7d70a5c..bf461eb 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.16.4.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-1.16.4.mdx @@ -1,4 +1,6 @@ -# Upgrade to v1.16.4 +--- +title: Upgrade to v1.16.4 +--- Thursday, 25th September, 2025 diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10002-rc2.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10002-rc2.mdx index d91c5d3..6e35340 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10002-rc2.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10002-rc2.mdx @@ -1,9 +1,8 @@ --- sidebar_position: 4 +title: Upgrade to 10002-rc2 --- -# Upgrade to 10002-rc2 - November 15th, 2021 Following [proposal #70](https://injhub.com/proposals/70) This indicates that the upgrade procedure should be performed on block number **4, 594, 100** diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10003-rc1.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10003-rc1.mdx index 2644798..b8f88eb 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10003-rc1.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10003-rc1.mdx @@ -1,9 +1,8 @@ --- sidebar_position: 5 +title: Upgrade to 10003-rc1 --- -# Upgrade to 10003-rc1 - Thursday, December 30th, 2021 Following [proposal #93](https://injhub.com/proposals/93) This indicates that the upgrade procedure should be performed on block number **6159200** diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10004-rc1-patch.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10004-rc1-patch.mdx index 5a5dd34..92297af 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10004-rc1-patch.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10004-rc1-patch.mdx @@ -1,9 +1,8 @@ --- sidebar_position: 7 +title: Upgrade to 10004-rc1-patch --- -# Upgrade to 10004-rc1-patch - Sunday, February 20th, 2022 Upgrade Injective from 10004-rc1 to 10004-rc1 [patch version 10004-rc1-1645352045](https://github.com/InjectiveLabs/injective-chain-releases/releases/tag/v1.4.0-1645352045) created due to an incident that happened on Sunday, February 20th, 2022, at 3:55 AM UTC-05:00, when [Network halted at block 7941974](https://explorer.injective.network/block/7941974). diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10004-rc1.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10004-rc1.mdx index f77f04f..4c8661c 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10004-rc1.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10004-rc1.mdx @@ -1,9 +1,8 @@ --- sidebar_position: 6 +title: Upgrade to 10004-rc1 --- -# Upgrade to 10004-rc1 - Tuesday, January 25th, 2022 Following [proposal #106](https://injhub.com/proposals/106) This indicates that the upgrade procedure should be performed on block number **7067700** diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10005-rc1.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10005-rc1.mdx index ac4c79c..29d38ba 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10005-rc1.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10005-rc1.mdx @@ -1,9 +1,8 @@ --- sidebar_position: 8 +title: Upgrade to 10005-rc1 --- -# Upgrade to 10005-rc1 - Monday, April 11th, 2022 Following [proposal #133](https://injhub.com/proposals/133) This indicates that the upgrade procedure should be performed on block number **9614200** diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10006-rc1.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10006-rc1.mdx index 5e528c4..2a54baa 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10006-rc1.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10006-rc1.mdx @@ -1,9 +1,8 @@ --- sidebar_position: 9 +title: Upgrade to 10006-rc1 --- -# Upgrade to 10006-rc1 - Tuesday, July 5th, 2022 Following [proposal 159](https://injhub.com/proposals/159/) This indicates that the upgrade procedure should be performed on block number **12569420** diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10007-rc1.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10007-rc1.mdx index c4647be..c414842 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10007-rc1.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10007-rc1.mdx @@ -1,9 +1,8 @@ --- sidebar_position: 10 +title: Upgrade to 10007-rc1 --- -# Upgrade to 10007-rc1 - Thursday, September 1st, 2022 Following [proposal 170)](https://injhub.com/proposals/170/) This indicates that the upgrade procedure should be performed on block number **14731000** diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10008.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10008.mdx index d17f210..fdee062 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10008.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10008.mdx @@ -1,9 +1,8 @@ --- sidebar_position: 11 +title: Upgrade to 10008 - Camelot --- -# Upgrade to 10008 - Camelot - Thursday, November 21st, 2022 Following [proposal 182](https://injhub.com/proposals/182/) This indicates that the upgrade procedure should be performed on block number **19761600** diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10009.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10009.mdx index 8f16ca3..ade3ee1 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10009.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-10009.mdx @@ -1,9 +1,8 @@ --- sidebar_position: 12 +title: Upgrade to 10009 --- -# Upgrade to 10009 - Tuesday, January 18th, 2022 Following [proposal 198](https://injhub.com/proposals/198/) This indicates that the upgrade procedure should be performed on block number **24204000** diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-v1.10.0.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-v1.10.0.mdx index 7e28f49..2db2cb2 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-v1.10.0.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-v1.10.0.mdx @@ -1,4 +1,6 @@ -# Upgrade to v1.10 +--- +title: Upgrade to v1.10 +--- Friday, March 17th, 2023 diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-v1.11.0.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-v1.11.0.mdx index 8dabee1..b872309 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-v1.11.0.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-v1.11.0.mdx @@ -1,9 +1,8 @@ --- sidebar_position: 13 +title: Upgrade to v1.11 --- -# Upgrade to v1.11 - Thursday, June 1st, 2023 Following [proposal 231](https://injhub.com/proposals/231/) This indicates that the upgrade procedure should be performed on block number **34775000** diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-v1.12.0.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-v1.12.0.mdx index 3c17497..842de79 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-v1.12.0.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-v1.12.0.mdx @@ -1,9 +1,8 @@ --- sidebar_position: 14 +title: Upgrade to v1.12.0 --- -# Upgrade to v1.12.0 - Thursday, January 11th, 2024 Following [proposal 314](https://injhub.com/proposals/314/) This indicates that the upgrade procedure should be performed on block number **57076000** diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-v1.12.1.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-v1.12.1.mdx index f79435b..36c5025 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-v1.12.1.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade-v1.12.1.mdx @@ -1,4 +1,6 @@ -# Upgrade to v1.12.1 +--- +title: Upgrade to v1.12.1 +--- Monday, January 22nd, 2024 diff --git a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade.mdx b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade.mdx index f93b46a..813b522 100644 --- a/.gitbook/infra/validator-mainnet/canonical-chain-upgrade.mdx +++ b/.gitbook/infra/validator-mainnet/canonical-chain-upgrade.mdx @@ -1,4 +1,6 @@ -# Canonical Chain Upgrades +--- +title: Canonical Chain Upgrades +--- ## Verify release versions diff --git a/.gitbook/infra/validator-mainnet.mdx b/.gitbook/infra/validator-mainnet/index.mdx similarity index 98% rename from .gitbook/infra/validator-mainnet.mdx rename to .gitbook/infra/validator-mainnet/index.mdx index 5ce4f33..5719b5f 100644 --- a/.gitbook/infra/validator-mainnet.mdx +++ b/.gitbook/infra/validator-mainnet/index.mdx @@ -1,4 +1,6 @@ -# Mainnet +--- +title: Mainnet +--- Node operators should deploy bare metal servers to achieve optimal performance. Additionally, validator nodes must meet the recommended hardware specifications and particularly the CPU requirements, to ensure high uptime. @@ -149,4 +151,4 @@ That's it! Once you've connected your validator identity with Keybase, the Injec #### Next Steps -Next, proceed to set up your [Ethereum Bridge Relayer](peggo.md). This is a necessary step to prevent your validator from being slashed. You should do this immediately after setting up your validator. +Next, proceed to set up your [Ethereum Bridge Relayer](./peggo/). This is a necessary step to prevent your validator from being slashed. You should do this immediately after setting up your validator. diff --git a/.gitbook/infra/validator-mainnet/peggo.mdx b/.gitbook/infra/validator-mainnet/peggo.mdx index e92ddaa..de82ab3 100644 --- a/.gitbook/infra/validator-mainnet/peggo.mdx +++ b/.gitbook/infra/validator-mainnet/peggo.mdx @@ -1,4 +1,6 @@ -# Peggo +--- +title: Peggo +--- If you're on this page then you've probably become a Validator on Injective. Congratulations! Configuring `peggo` is the final step of your setup. diff --git a/.gitbook/infra/validator-testnet.mdx b/.gitbook/infra/validator-testnet/index.mdx similarity index 98% rename from .gitbook/infra/validator-testnet.mdx rename to .gitbook/infra/validator-testnet/index.mdx index 59e9a8d..3919ac0 100644 --- a/.gitbook/infra/validator-testnet.mdx +++ b/.gitbook/infra/validator-testnet/index.mdx @@ -1,4 +1,6 @@ -# Testnet +--- +title: Testnet +--- Node operators should deploy bare metal servers to achieve optimal performance. Additionally, validator nodes must meet the recommended hardware specifications and particularly the CPU requirements, to ensure high uptime. @@ -119,7 +121,7 @@ You can check that your validator was successfully created by checking the [staking dashboard](https://injhub.com/stake/), and scrolling down to the "Validators" section. It looks like this: -![Inj Hub Staking Validators Section](../../.gitbook/assets/inj-hub-staking-validators-section.png) +![Inj Hub Staking Validators Section](/img/inj-hub-staking-validators-section.png) Alternatively, enter the following CLI command: diff --git a/.gitbook/infra/validator-testnet/peggo.mdx b/.gitbook/infra/validator-testnet/peggo.mdx index d6572b2..9a3dcfe 100644 --- a/.gitbook/infra/validator-testnet/peggo.mdx +++ b/.gitbook/infra/validator-testnet/peggo.mdx @@ -1,4 +1,6 @@ -# Testnet Peggo +--- +title: Testnet Peggo +--- ## Equinox Testnet diff --git a/.gitbook/references.mdx b/.gitbook/references.mdx index 224fcde..1dae41d 100644 --- a/.gitbook/references.mdx +++ b/.gitbook/references.mdx @@ -1,9 +1,8 @@ --- description: Important references and links for the Injective Ecosystem +title: References --- -# References - ## Developer Resources ### Developer Tools and Resources @@ -13,13 +12,13 @@ Developer tools and resources to get you building on Injective | **Resource** | **Description** | | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | [Injective 101](https://injective.notion.site/Injective-101-589dedc4c9c04531aae503dbb235d443) | One-stop-shop for Injective resources | -| [Injectived](./developers/injectived/README.md) | Command-line interface and node daemon that connects to Injective | +| [Injectived](./developers/injectived/) | Command-line interface and node daemon that connects to Injective | | [Injective Explorer](https://explorer.injective.network/) | Analytics platform that enables anyone to search addresses, trades, tokens, transactions, and other activities on Injective | | [Injective Local](https://github.com/InjectiveLabs/injective-local) | Injective testnet and ecosystem containerized with Docker and orchestrated with a simple docker-compose file. | | [Injective REST API](https://lcd.injective.network/swagger/) | Swagger API explorer | | [Injective TypeScript SDK](https://docs.ts.injective.network) | Build dApps on Injectuve using TypeScript | | [Injective API Reference](https://api.injective.exchange) | Detailed API documentation for interacting with Injective for traders | -| [Cosmovisor](./infra/cosmovisor.md) | Small process manager around Cosmos SDK binaries that monitors the governance module | +| [Cosmovisor](./infra/cosmovisor/) | Small process manager around Cosmos SDK binaries that monitors the governance module | | [CosmosSDK](https://docs.cosmos.network/main/build) | The Cosmos SDK documentation serving as a valuable resource for developers integrating with the Injective ecosystem | ### Ecosystem Tools and Resources @@ -65,8 +64,8 @@ Find developer support on Discord or Telegram ### Public Endpoints -For a list of public endpoints, visit [public endpoints](./infra/public-endpoints.md "mention") +For a list of public endpoints, visit [public endpoints](./infra/public-endpoints/ "mention") ### Private / Dedicated Node Services -For a full list of private node services, see [premium endpoints](infra/premium-endpoints.md "mention") +For a full list of private node services, see [premium endpoints](./infra/premium-endpoints/ "mention") diff --git a/scripts/copy-injective-docs.sh b/scripts/copy-injective-docs.sh index 8e613c7..09fc138 100755 --- a/scripts/copy-injective-docs.sh +++ b/scripts/copy-injective-docs.sh @@ -1,10 +1,23 @@ #!/usr/bin/env bash +# extracts markdown files from specs directories of cosmos-sdk and injective-core repos, +# and places them within /developers-native/ in this repo + +## config injective_core_branch=master cosmos_sdk_branch=v0.50.x-inj -BUILD_DIR=./temp -STUB_DIR=./scripts/stub -CORE_DIR=./.gitbook/developers-native/core -INJECTIVE_DIR=./.gitbook/developers-native/injective +SCRIPTS_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) +echo "SCRIPTS_DIR=${SCRIPTS_DIR}" +DIR=$( cd -- "${SCRIPTS_DIR}/../.gitbook" &> /dev/null && pwd ) +BUILD_DIR="${SCRIPTS_DIR}/temp" +STUB_DIR="${SCRIPTS_DIR}/stub" +CORE_DIR="${DIR}/developers-native/core" +INJECTIVE_DIR="${DIR}/developers-native/injective" +SKIP_CLONE="" +SKIP_TEARDOWN="" +echo "BUILD_DIR=${BUILD_DIR}" +echo "STUB_DIR=${STUB_DIR}" +echo "CORE_DIR=${CORE_DIR}" +echo "INJECTIVE_DIR=${INJECTIVE_DIR}" mkdir -p $BUILD_DIR rm -rf $CORE_DIR @@ -12,6 +25,7 @@ rm -rf $INJECTIVE_DIR mkdir -p $CORE_DIR mkdir -p $INJECTIVE_DIR +## clone repos if [ "$GH_CORE_USER" ] && [ "$GH_CORE_TOKEN" ]; then echo "Using GitHub credentials for cloning injective-core" INJ_CORE_GIT_URL="https://${GH_CORE_USER}:${GH_CORE_TOKEN}@github.com/InjectiveLabs/injective-core.git" @@ -19,66 +33,92 @@ else echo "Using org access to clone injective-core" INJ_CORE_GIT_URL="org-44571224@github.com:InjectiveLabs/injective-core.git" fi -git clone "${INJ_CORE_GIT_URL}" "${BUILD_DIR}/injective-core" \ - -b "${injective_core_branch}" \ - --depth 1 \ - --single-branch > /dev/null +if [ "${SKIP_CLONE}" = "true" ]; then + git clone "${INJ_CORE_GIT_URL}" "${BUILD_DIR}/injective-core" \ + -b "${injective_core_branch}" \ + --depth 1 \ + --single-branch > /dev/null +else + echo "SKIPPED: clone of injective-core" +fi echo "Cloning cosmos-sdk..." -git clone "https://github.com/InjectiveLabs/cosmos-sdk.git" "${BUILD_DIR}/cosmos-sdk" \ - -b "${cosmos_sdk_branch}" \ - --depth 1 \ - --single-branch > /dev/null +if [ "${SKIP_CLONE}" = "true" ]; then + git clone "https://github.com/InjectiveLabs/cosmos-sdk.git" "${BUILD_DIR}/cosmos-sdk" \ + -b "${cosmos_sdk_branch}" \ + --depth 1 \ + --single-branch > /dev/null +else + echo "SKIPPED: clone of cosmos-sdk" +fi ## Generate errors docs ./$BUILD_DIR/injective-core/scripts/docs/generate_errors_docs.sh -# copy from the cosmos-sdk repo files x/*/README.md into this repo -for D in ./$BUILD_DIR/cosmos-sdk/x/*; do +## copy from the cosmos-sdk repo files x/*/README.md into this repo +echo "===CORE_DIR===" +ls $BUILD_DIR/cosmos-sdk/x/* +for D in $BUILD_DIR/cosmos-sdk/x/*; do if [ -d "${D}" ]; then - mkdir -p "$CORE_DIR/$(echo $D | awk -F/ '{print $NF}')" && cp -r $D/README.md "$_" + mkdir -p "$CORE_DIR/$(echo $D | awk -F/ '{print $NF}')" && \ + cp -r $D/README.md "$_/index.md" && \ + rm "$_/index.mde*" fi done -# copy from the injective-core repo files injective-chain/modules/*/spec/* into this repo -for D in ./$BUILD_DIR/injective-core/injective-chain/modules/*; do +## copy from the injective-core repo files injective-chain/modules/*/spec/* into this repo +echo "===INJECTIVE_DIR===" +ls $BUILD_DIR/injective-core/injective-chain/modules/* +for D in $BUILD_DIR/injective-core/injective-chain/modules/*; do if [ -d "${D}" ]; then - mkdir -p "$INJECTIVE_DIR/$(echo $D | awk -F/ '{print $NF}')" && cp -r $D/spec/* "$_" + mkdir -p "$INJECTIVE_DIR/$(echo $D | awk -F/ '{print $NF}')" && \ + cp -r $D/spec/* "$_" && \ + mv "$_/README.md" "$_/index.md" && \ + rm "$_/index.mde*" fi done ## txfees -cp $BUILD_DIR/injective-core/injective-chain/modules/txfees/README.md $INJECTIVE_DIR/txfees/README.md +cp $BUILD_DIR/injective-core/injective-chain/modules/txfees/README.md $INJECTIVE_DIR/txfees/index.md ## lanes mkdir -p $INJECTIVE_DIR/lanes -cp $BUILD_DIR/injective-core/injective-chain/lanes/spec/README.md $INJECTIVE_DIR/lanes/README.md +cp $BUILD_DIR/injective-core/injective-chain/lanes/spec/README.md $INJECTIVE_DIR/lanes/index.md -cp $STUB_DIR/core.modules.md.stub $CORE_DIR/README.md -cp $STUB_DIR/injective.modules.md.stub $INJECTIVE_DIR/README.md +## Manually replace wrong relative paths for links -## 1. Manually replace wrong import paths -## authz +### authz search1="(../modules/auth/)" replace1="(../auth/)" - FILES=$( find $CORE_DIR/authz -type f ) - for file in $FILES do sed -ie "s/${search1//\//\\/}/${replace1//\//\\/}/g" $file done -## auth +### auth search2="(../modules/authz/)" replace2="(../authz/)" - FILES=$( find $CORE_DIR/auth -type f ) - for file in $FILES do sed -ie "s/${search2//\//\\/}/${replace2//\//\\/}/g" $file done -rm $CORE_DIR/authz/README.mde -rm $CORE_DIR/auth/README.mde -rm -rf $BUILD_DIR +### READMEs +FILES=$( find $CORE_DIR/ -type f ) +for file in $FILES +do + sed -ie "s/\/README\.md/\//g" $file +done + +## stubs +cp $STUB_DIR/core.modules.md.stub $CORE_DIR/index.md +cp $STUB_DIR/injective.modules.md.stub $INJECTIVE_DIR/index.md + +## tear down +echo "Clean up..." +if [ "${SKIP_TEARDOWN}" = "true" ]; then + rm -rf $BUILD_DIR $STUB_DIR +else + echo "SKIPPED: clone of BUILD_DIR and STUB_DIR" +fi \ No newline at end of file