Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v0.36.0 upgrade #625

Merged
merged 5 commits into from
Jun 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/delete-branch-snapshot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:
steps:
- name: Retrieve post upgrade snapshot generator binary
run: |
POST_UPGRADE_SNAPSHOT_GENERATOR_VERSION=v0.2.2
POST_UPGRADE_SNAPSHOT_GENERATOR_VERSION=v0.2.5
DOWNLOAD_URL=https://github.com/elys-network/post-upgrade-snapshot-generator/releases/download/${POST_UPGRADE_SNAPSHOT_GENERATOR_VERSION}/post-upgrade-snapshot-generator-${POST_UPGRADE_SNAPSHOT_GENERATOR_VERSION}-linux-amd64
POST_UPGRADE_SNAPSHOT_GENERATOR_PATH=/tmp/post-upgrade-snapshot-generator-${POST_UPGRADE_SNAPSHOT_GENERATOR_VERSION}
curl -L $DOWNLOAD_URL -o $POST_UPGRADE_SNAPSHOT_GENERATOR_PATH && chmod +x $POST_UPGRADE_SNAPSHOT_GENERATOR_PATH
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/software-upgrade-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ jobs:

- name: Retrieve post upgrade snapshot generator binary
run: |
POST_UPGRADE_SNAPSHOT_GENERATOR_VERSION=v0.2.2
POST_UPGRADE_SNAPSHOT_GENERATOR_VERSION=v0.2.5
DOWNLOAD_URL=https://github.com/elys-network/post-upgrade-snapshot-generator/releases/download/${POST_UPGRADE_SNAPSHOT_GENERATOR_VERSION}/post-upgrade-snapshot-generator-${POST_UPGRADE_SNAPSHOT_GENERATOR_VERSION}-linux-amd64
POST_UPGRADE_SNAPSHOT_GENERATOR_PATH=/tmp/post-upgrade-snapshot-generator-${POST_UPGRADE_SNAPSHOT_GENERATOR_VERSION}
curl -L $DOWNLOAD_URL -o $POST_UPGRADE_SNAPSHOT_GENERATOR_PATH && chmod +x $POST_UPGRADE_SNAPSHOT_GENERATOR_PATH
Expand All @@ -56,7 +56,7 @@ jobs:
echo "NEW_BINARY_PATH=$NEW_BINARY_PATH" >> $GITHUB_ENV

- name: Check submit new proposal from cache exists
uses: elys-network/actions-cache-s3@eba1d2b54699fda7ee03d826049bc67dcf514887
uses: elys-network/actions-cache-s3/restore@eba1d2b54699fda7ee03d826049bc67dcf514887
id: cache-submit-new-proposal
with:
path: |
Expand Down Expand Up @@ -93,7 +93,7 @@ jobs:
if: steps.cache-submit-new-proposal.outputs.cache-hit != 'true'

- name: Check snapshot from cache exists
uses: elys-network/actions-cache-s3@eba1d2b54699fda7ee03d826049bc67dcf514887
uses: elys-network/actions-cache-s3/restore@eba1d2b54699fda7ee03d826049bc67dcf514887
id: cache-snapshot-exists
with:
path: |
Expand Down
10 changes: 5 additions & 5 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -823,7 +823,7 @@ func NewElysApp(
app.GetSubspace(masterchefmoduletypes.ModuleName),
app.ParameterKeeper,
app.CommitmentKeeper,
app.AmmKeeper,
&app.AmmKeeper,
app.OracleKeeper,
app.AssetprofileKeeper,
app.AccountedPoolKeeper,
Expand All @@ -844,7 +844,7 @@ func NewElysApp(
app.StakingKeeper,
app.AccountKeeper,
app.BankKeeper,
app.AmmKeeper,
&app.AmmKeeper,
app.OracleKeeper,
app.AssetprofileKeeper,
app.AccountedPoolKeeper,
Expand Down Expand Up @@ -982,7 +982,7 @@ func NewElysApp(
keys[perpetualmoduletypes.StoreKey],
keys[perpetualmoduletypes.MemStoreKey],
authtypes.NewModuleAddress(govtypes.ModuleName).String(),
app.AmmKeeper,
&app.AmmKeeper,
app.BankKeeper,
app.OracleKeeper,
app.AssetprofileKeeper,
Expand All @@ -1003,7 +1003,7 @@ func NewElysApp(
keys[leveragelpmoduletypes.StoreKey],
keys[leveragelpmoduletypes.MemStoreKey],
authtypes.NewModuleAddress(govtypes.ModuleName).String(),
app.AmmKeeper,
&app.AmmKeeper,
app.BankKeeper,
app.OracleKeeper,
app.StablestakeKeeper,
Expand All @@ -1021,7 +1021,7 @@ func NewElysApp(
app.BankKeeper,
app.OracleKeeper,
app.AssetprofileKeeper,
app.AmmKeeper,
&app.AmmKeeper,
app.EstakingKeeper,
app.MasterchefKeeper,
app.CommitmentKeeper,
Expand Down
4 changes: 2 additions & 2 deletions scripts/examples/leveragelp/leveragelp.sh
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ elysd tx gov vote 3 Yes --from=treasury --keyring-backend=test --chain-id=elyste
elysd query gov proposals

# Open position
elysd tx leveragelp open 5.0 uusdc 500000 1 0.0 --from=treasury --keyring-backend=test --chain-id=elystestnet-1 --yes --gas=1000000 --fees=250uelys
elysd tx leveragelp open 5.0 uusdc 5000000 1 0.0 --from=treasury --keyring-backend=test --chain-id=elystestnet-1 --yes --gas=1000000 --fees=250uelys
elysd tx leveragelp open [leverage] [collateral-asset] [collateral-amount] [amm-pool-id] [flags]

# Close position
elysd tx leveragelp close 1 --from=treasury --keyring-backend=test --chain-id=elystestnet-1 --yes --gas=1000000
elysd tx leveragelp close 1 500000000000000000 --from=treasury --keyring-backend=test --chain-id=elystestnet-1 --yes --gas=1000000
elysd tx leveragelp close [position-id] [flags]

# Query rewards
Expand Down
83 changes: 83 additions & 0 deletions x/accountedpool/spec/01_concepts.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,86 @@ order: 1
# Concepts

The `accountedpool` module in the Elys Network manages accounted pools, ensuring accurate accounting of assets within pools. It integrates with Automated Market Maker (AMM) and Perpetual pools, updating pool states based on their activities.

## Module Components

1. **Keeper**: The core component that handles the business logic of the `AccountedPool` module.
2. **Hooks**: Functions that trigger updates to the accounted pool based on specific events in the AMM and Perpetual modules.

## Key Functions

### 1. `UpdateAccountedPool`

The `UpdateAccountedPool` function is responsible for recalculating and updating the balance of an accounted pool. It performs the following steps:

- **Check Pool Existence**: Ensures the pool exists before attempting to update it.
- **Retrieve Accounted Pool**: Fetches the current state of the accounted pool.
- **Calculate New Balance**: Computes the new balance of the accounted pool by summing the balances from the AMM pool and the Perpetual pool, including liabilities but excluding already deducted custody amounts.
- **Update State**: Saves the updated accounted pool state back to the store.

**Function Signature**:

```go
func (k Keeper) UpdateAccountedPool(ctx sdk.Context, ammPool ammtypes.Pool, perpetualPool perpetualtypes.Pool) error
```

**Parameters**:

- `ctx`: The context of the current transaction.
- `ammPool`: The AMM pool instance.
- `perpetualPool`: The Perpetual pool instance.

**Return**:

- Returns an error if the pool does not exist or if there is an issue retrieving balances.

### 2. `InitiateAccountedPool`

The `InitiateAccountedPool` function is called after the creation of a new AMM pool to initialize its corresponding accounted pool.

**Function Signature**:

```go
func (k Keeper) InitiateAccountedPool(ctx sdk.Context, ammPool ammtypes.Pool)
```

**Parameters**:

- `ctx`: The context of the current transaction.
- `ammPool`: The AMM pool instance.

## Hooks

Hooks are specialized functions that automatically trigger updates to the accounted pool based on specific actions within the AMM and Perpetual modules. These actions include opening, modifying, or closing perpetual positions, as well as creating, joining, exiting, or swapping in AMM pools.

**Hook Functions**:

- **AfterPerpetualPositionOpen**
- **AfterPerpetualPositionModified**
- **AfterPerpetualPositionClosed**
- **AfterAmmPoolCreated**
- **AfterAmmJoinPool**
- **AfterAmmExitPool**
- **AfterAmmSwap**

Each hook function calls `UpdateAccountedPool` or `InitiateAccountedPool` as appropriate, ensuring the accounted pool's state remains consistent with the latest transactions.

**Example**:

```go
func (k Keeper) AfterPerpetualPositionOpen(ctx sdk.Context, ammPool ammtypes.Pool, perpetualPool perpetualtypes.Pool, sender string) {
k.UpdateAccountedPool(ctx, ammPool, perpetualPool)
}
```

## Error Handling

The `AccountedPool` module includes error handling to manage cases where pools do not exist or balances cannot be retrieved. Notable errors include:

- `types.ErrPoolDoesNotExist`

These errors ensure that the module can gracefully handle unexpected states and provide meaningful feedback for debugging and resolution.

## Integration

The `AccountedPool` module integrates with the AMM and Perpetual modules, leveraging their pool data to maintain an accurate and up-to-date accounted pool state. By responding to various lifecycle events in these modules, the `AccountedPool` module ensures comprehensive and dynamic pool management.
4 changes: 3 additions & 1 deletion x/leveragelp/keeper/position.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,9 @@ func (k Keeper) DestroyPosition(ctx sdk.Context, positionAddress string, id uint

// decrement open position count
openCount := k.GetOpenPositionCount(ctx)
openCount--
if openCount != 0 {
openCount--
}

// Set open Position count
k.SetOpenPositionCount(ctx, openCount)
Expand Down
11 changes: 11 additions & 0 deletions x/leveragelp/migrations/v5_migration.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package migrations

import (
sdk "github.com/cosmos/cosmos-sdk/types"
)

func (m Migrator) V5Migration(ctx sdk.Context) error {
count := m.keeper.GetPositionCount(ctx)
m.keeper.SetOpenPositionCount(ctx, count)
return nil
}
4 changes: 2 additions & 2 deletions x/leveragelp/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ func (am AppModule) RegisterServices(cfg module.Configurator) {
types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper))
types.RegisterQueryServer(cfg.QueryServer(), am.keeper)
m := migrations.NewMigrator(am.keeper)
err := cfg.RegisterMigration(types.ModuleName, 3, m.V4Migration)
err := cfg.RegisterMigration(types.ModuleName, 4, m.V5Migration)
if err != nil {
panic(err)
}
Expand All @@ -144,7 +144,7 @@ func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.Raw
}

// ConsensusVersion is a sequence number for state-breaking change of the module. It should be incremented on each consensus-breaking change introduced by the module. To avoid wrong/empty versions, the initial version should be set to 1
func (AppModule) ConsensusVersion() uint64 { return 4 }
func (AppModule) ConsensusVersion() uint64 { return 5 }

// BeginBlock contains the logic that is automatically triggered at the beginning of each block
func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) {
Expand Down
7 changes: 3 additions & 4 deletions x/masterchef/keeper/hooks_masterchef.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ func (k Keeper) UpdateAccPerShare(ctx sdk.Context, poolId uint64, rewardDenom st
return
}
poolRewardInfo.PoolAccRewardPerShare = poolRewardInfo.PoolAccRewardPerShare.Add(
math.LegacyNewDecFromInt(amount.Mul(ammtypes.OneShare)).
Quo(math.LegacyNewDecFromInt(totalCommit)),
math.LegacyNewDecFromInt(amount.Mul(ammtypes.OneShare)).QuoInt(totalCommit),
)
poolRewardInfo.LastUpdatedBlock = uint64(ctx.BlockHeight())
k.SetPoolRewardInfo(ctx, poolRewardInfo)
Expand Down Expand Up @@ -83,9 +82,9 @@ func (k Keeper) UpdateUserRewardPending(ctx sdk.Context, poolId uint64, rewardDe

userRewardInfo.RewardPending = userRewardInfo.RewardPending.Add(
poolRewardInfo.PoolAccRewardPerShare.
Mul(math.LegacyNewDecFromInt(userBalance)).
MulInt(userBalance).
Sub(userRewardInfo.RewardDebt).
Quo(math.LegacyNewDecFromInt(ammtypes.OneShare)),
QuoInt(ammtypes.OneShare),
)

k.SetUserRewardInfo(ctx, userRewardInfo)
Expand Down
2 changes: 2 additions & 0 deletions x/masterchef/keeper/msg_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,9 @@ func (k Keeper) ClaimRewards(ctx sdk.Context, sender sdk.AccAddress, poolIds []u
sdk.NewEvent(
types.TypeEvtClaimRewards,
sdk.NewAttribute(types.AttributeSender, sender.String()),
sdk.NewAttribute(types.AttributeRecipient, recipient.String()),
sdk.NewAttribute(types.AttributePoolId, fmt.Sprintf("%d", poolId)),
sdk.NewAttribute(sdk.AttributeKeyAmount, coin.String()),
),
})
}
Expand Down
1 change: 1 addition & 0 deletions x/masterchef/types/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@ const (
AttributeToBlock = "to_block"
AttributeAmountPerBlock = "amount_per_block"
AttributeSender = "sender"
AttributeRecipient = "recipient"
AttributeMultiplier = "multiplier"
)
13 changes: 13 additions & 0 deletions x/stablestake/keeper/debt.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package keeper
import (
"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/elys-network/elys/x/stablestake/types"
)

Expand Down Expand Up @@ -81,6 +82,18 @@ func (k Keeper) Borrow(ctx sdk.Context, addr sdk.AccAddress, amount sdk.Coin) er
if depositDenom != amount.Denom {
return types.ErrInvalidBorrowDenom
}

// For security reasons, we should avoid borrowing more than 90% in total to the stablestake pool.
moduleAddr := authtypes.NewModuleAddress(types.ModuleName)
params := k.GetParams(ctx)
balance := k.bk.GetBalance(ctx, moduleAddr, depositDenom)

borrowed := params.TotalValue.Sub(balance.Amount).ToLegacyDec().Add(amount.Amount.ToLegacyDec())
maxAllowed := params.TotalValue.ToLegacyDec().Mul(sdk.NewDec(9)).Quo(sdk.NewDec(10))
if borrowed.GT(maxAllowed) {
return types.ErrMaxBorrowAmount
}

debt := k.UpdateInterestStackedByAddress(ctx, addr)
debt.Borrowed = debt.Borrowed.Add(amount.Amount)
k.SetDebt(ctx, debt)
Expand Down
1 change: 1 addition & 0 deletions x/stablestake/types/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ var (
ErrInvalidBorrowDenom = errorsmod.Register(ModuleName, 2, "invalid borrow denom")
ErrRedemptionRateIsZero = errorsmod.Register(ModuleName, 3, "redemption rate is zero")
ErrNegativeBorrowed = errorsmod.Register(ModuleName, 4, "negative borrowed amount")
ErrMaxBorrowAmount = errorsmod.Register(ModuleName, 5, "cannot borrow more than 90% of total stablestake pool.")
)
Loading