Skip to content

Commit

Permalink
feat: message withdraw emissions (#1825)
Browse files Browse the repository at this point in the history
  • Loading branch information
kingpinXD authored Mar 5, 2024
1 parent 422e00e commit 589e228
Show file tree
Hide file tree
Showing 22 changed files with 1,192 additions and 22 deletions.
1 change: 1 addition & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
### Features

* [1698](https://github.com/zeta-chain/node/issues/1698) - bitcoin dynamic depositor fee
* [1811](https://github.com/zeta-chain/node/pull/1811) - add a message to withdraw emission rewards

### Docs

Expand Down
1 change: 1 addition & 0 deletions docs/cli/zetacored/zetacored_tx_emissions.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@ zetacored tx emissions [flags]
### SEE ALSO

* [zetacored tx](zetacored_tx.md) - Transactions subcommands
* [zetacored tx emissions withdraw-emission](zetacored_tx_emissions_withdraw-emission.md) - create a new withdrawEmission

52 changes: 52 additions & 0 deletions docs/cli/zetacored/zetacored_tx_emissions_withdraw-emission.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# tx emissions withdraw-emission

create a new withdrawEmission

```
zetacored tx emissions withdraw-emission [amount] [flags]
```

### Options

```
-a, --account-number uint The account number of the signing account (offline mode only)
--aux Generate aux signer data instead of sending a tx
-b, --broadcast-mode string Transaction broadcasting mode (sync|async|block)
--dry-run ignore the --gas flag and perform a simulation of a transaction, but don't broadcast it (when enabled, the local Keybase is not accessible)
--fee-granter string Fee granter grants fees for the transaction
--fee-payer string Fee payer pays fees for the transaction instead of deducting from the signer
--fees string Fees to pay along with transaction; eg: 10uatom
--from string Name or address of private key with which to sign
--gas string gas limit to set per-transaction; set to "auto" to calculate sufficient gas automatically. Note: "auto" option doesn't always report accurate results. Set a valid coin value to adjust the result. Can be used instead of "fees". (default 200000)
--gas-adjustment float adjustment factor to be multiplied against the estimate returned by the tx simulation; if the gas limit is set manually this flag is ignored (default 1)
--gas-prices string Gas prices in decimal format to determine the transaction fee (e.g. 0.1uatom)
--generate-only Build an unsigned transaction and write it to STDOUT (when enabled, the local Keybase only accessed when providing a key name)
-h, --help help for withdraw-emission
--keyring-backend string Select keyring's backend (os|file|kwallet|pass|test|memory)
--keyring-dir string The client Keyring directory; if omitted, the default 'home' directory will be used
--ledger Use a connected Ledger device
--node string [host]:[port] to tendermint rpc interface for this chain
--note string Note to add a description to the transaction (previously --memo)
--offline Offline mode (does not allow any online functionality)
-o, --output string Output format (text|json)
-s, --sequence uint The sequence number of the signing account (offline mode only)
--sign-mode string Choose sign mode (direct|amino-json|direct-aux), this is an advanced feature
--timeout-height uint Set a block timeout height to prevent the tx from being committed past a certain height
--tip string Tip is the amount that is going to be transferred to the fee payer on the target chain. This flag is only valid when used with --aux, and is ignored if the target chain didn't enable the TipDecorator
-y, --yes Skip tx broadcasting prompt confirmation
```

### Options inherited from parent commands

```
--chain-id string The network chain ID
--home string directory for config and data
--log_format string The logging format (json|plain)
--log_level string The logging level (trace|debug|info|warn|error|fatal|panic)
--trace print out full stack trace on errors
```

### SEE ALSO

* [zetacored tx emissions](zetacored_tx_emissions.md) - emissions transactions subcommands

2 changes: 2 additions & 0 deletions docs/openapi/openapi.swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -54011,6 +54011,8 @@ definitions:
type: string
proved:
type: boolean
emissionsMsgWithdrawEmissionResponse:
type: object
emissionsQueryGetEmissionsFactorsResponse:
type: object
properties:
Expand Down
16 changes: 16 additions & 0 deletions docs/spec/emissions/messages.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Messages

## MsgWithdrawEmission

WithdrawEmission allows the user to withdraw from their withdrawable emissions.
on a successful withdrawal, the amount is transferred from the undistributed rewards pool to the user's account.
if the amount to be withdrawn is greater than the available withdrawable emission, the max available amount is withdrawn.
if the pool does not have enough balance to process this request, an error is returned.

```proto
message MsgWithdrawEmission {
string creator = 1;
string amount = 2;
}
```

14 changes: 13 additions & 1 deletion proto/emissions/tx.proto
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,16 @@ import "gogoproto/gogo.proto";
option go_package = "github.com/zeta-chain/zetacore/x/emissions/types";

// Msg defines the Msg service.
service Msg {}
service Msg {
rpc WithdrawEmission(MsgWithdrawEmission) returns (MsgWithdrawEmissionResponse);
}

message MsgWithdrawEmission {
string creator = 1;
string amount = 2 [
(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int",
(gogoproto.nullable) = false
];
}

message MsgWithdrawEmissionResponse {}
6 changes: 6 additions & 0 deletions testutil/keeper/emissions.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,9 @@ func EmissionKeeperWithMockOptions(

return k, ctx, sdkKeepers, zetaKeepers
}

func GetEmissionsBankMock(t testing.TB, keeper *keeper.Keeper) *emissionsmocks.EmissionBankKeeper {
cbk, ok := keeper.GetBankKeeper().(*emissionsmocks.EmissionBankKeeper)
require.True(t, ok)
return cbk
}
18 changes: 18 additions & 0 deletions testutil/keeper/mocks/emissions/bank.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 24 additions & 0 deletions testutil/keeper/mocks/emissions/emission.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions typescript/emissions/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export * from "./events_pb";
export * from "./genesis_pb";
export * from "./params_pb";
export * from "./query_pb";
export * from "./tx_pb";
export * from "./withdrawable_emissions_pb";
56 changes: 56 additions & 0 deletions typescript/emissions/tx_pb.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// @generated by protoc-gen-es v1.3.0 with parameter "target=dts"
// @generated from file emissions/tx.proto (package zetachain.zetacore.emissions, syntax proto3)
/* eslint-disable */
// @ts-nocheck

import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf";
import { Message, proto3 } from "@bufbuild/protobuf";

/**
* @generated from message zetachain.zetacore.emissions.MsgWithdrawEmission
*/
export declare class MsgWithdrawEmission extends Message<MsgWithdrawEmission> {
/**
* @generated from field: string creator = 1;
*/
creator: string;

/**
* @generated from field: string amount = 2;
*/
amount: string;

constructor(data?: PartialMessage<MsgWithdrawEmission>);

static readonly runtime: typeof proto3;
static readonly typeName = "zetachain.zetacore.emissions.MsgWithdrawEmission";
static readonly fields: FieldList;

static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): MsgWithdrawEmission;

static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): MsgWithdrawEmission;

static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): MsgWithdrawEmission;

static equals(a: MsgWithdrawEmission | PlainMessage<MsgWithdrawEmission> | undefined, b: MsgWithdrawEmission | PlainMessage<MsgWithdrawEmission> | undefined): boolean;
}

/**
* @generated from message zetachain.zetacore.emissions.MsgWithdrawEmissionResponse
*/
export declare class MsgWithdrawEmissionResponse extends Message<MsgWithdrawEmissionResponse> {
constructor(data?: PartialMessage<MsgWithdrawEmissionResponse>);

static readonly runtime: typeof proto3;
static readonly typeName = "zetachain.zetacore.emissions.MsgWithdrawEmissionResponse";
static readonly fields: FieldList;

static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): MsgWithdrawEmissionResponse;

static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): MsgWithdrawEmissionResponse;

static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): MsgWithdrawEmissionResponse;

static equals(a: MsgWithdrawEmissionResponse | PlainMessage<MsgWithdrawEmissionResponse> | undefined, b: MsgWithdrawEmissionResponse | PlainMessage<MsgWithdrawEmissionResponse> | undefined): boolean;
}

2 changes: 1 addition & 1 deletion x/emissions/client/cli/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ func GetTxCmd() *cobra.Command {
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}

cmd.AddCommand(CmdWithdrawEmission())
return cmd
}
37 changes: 37 additions & 0 deletions x/emissions/client/cli/tx_withdraw_emissions..go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package cli

import (
"errors"

sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/spf13/cobra"
"github.com/zeta-chain/zetacore/x/emissions/types"
)

func CmdWithdrawEmission() *cobra.Command {
cmd := &cobra.Command{
Use: "withdraw-emission [amount]",
Short: "create a new withdrawEmission",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
argsAmount, ok := sdkmath.NewIntFromString(args[0])
if !ok {
return errors.New("invalid amount")
}
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
msg := types.NewMsgWithdrawEmissions(clientCtx.GetFromAddress().String(), argsAmount)
if err := msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
45 changes: 45 additions & 0 deletions x/emissions/keeper/msg_server_withdraw_emissions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package keeper

import (
"context"
"fmt"

errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/zeta-chain/zetacore/cmd/zetacored/config"
"github.com/zeta-chain/zetacore/x/emissions/types"
)

// WithdrawEmission allows the user to withdraw from their withdrawable emissions.
// on a successful withdrawal, the amount is transferred from the undistributed rewards pool to the user's account.
// if the amount to be withdrawn is greater than the available withdrawable emission, the max available amount is withdrawn.
// if the pool does not have enough balance to process this request, an error is returned.
func (k msgServer) WithdrawEmission(goCtx context.Context, msg *types.MsgWithdrawEmission) (*types.MsgWithdrawEmissionResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)

// check if the creator address is valid
address, err := sdk.AccAddressFromBech32(msg.Creator)
if err != nil {
return nil, errorsmod.Wrap(types.ErrInvalidAddress, err.Error())
}

// check if the undistributed rewards pool has enough balance to process this request.
// This is just a preliminary check, the actual processing at endblock might still fail if the pool balance gets affected.
undistributedRewardsBalance := k.GetBankKeeper().GetBalance(ctx, types.UndistributedObserverRewardsPoolAddress, config.BaseDenom)
if undistributedRewardsBalance.Amount.LT(msg.Amount) {
return nil, errorsmod.Wrap(types.ErrRewardsPoolDoesNotHaveEnoughBalance, " rewards pool does not have enough balance to process this request")
}

err = k.RemoveWithdrawableEmission(ctx, msg.Creator, msg.Amount)
if err != nil {
return nil, errorsmod.Wrap(types.ErrUnableToWithdrawEmissions, fmt.Sprintf("error while removing withdrawable emission for address %s : %s", msg.Creator, err))
}

err = k.GetBankKeeper().SendCoinsFromModuleToAccount(ctx, types.UndistributedObserverRewardsPool, address, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, msg.Amount)))
if err != nil {
ctx.Logger().Error(fmt.Sprintf("Error while processing withdraw of emission to adresss %s for amount %s : err %s", address, msg.Amount, err))
return nil, errorsmod.Wrap(types.ErrUnableToWithdrawEmissions, err.Error())
}

return &types.MsgWithdrawEmissionResponse{}, nil
}
Loading

0 comments on commit 589e228

Please sign in to comment.