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

Add claimsmanager udpate spec. #1788

Draft
wants to merge 14 commits into
base: main
Choose a base branch
from
Draft
13 changes: 13 additions & 0 deletions app/keepers/keepers.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,10 +365,23 @@
appKeepers.ICAModule = ica.NewAppModule(&appKeepers.ICAControllerKeeper, &appKeepers.ICAHostKeeper)
icaHostIBCModule := icahost.NewIBCModule(appKeepers.ICAHostKeeper)

// todo : fix cyclical issue of claimsmanagerkeeper
// reason :
//imports github.com/quicksilver-zone/quicksilver/app

Check failure on line 370 in app/keepers/keepers.go

View workflow job for this annotation

GitHub Actions / lint

commentFormatting: put a space between `//` and comment text (gocritic)
//imports github.com/quicksilver-zone/quicksilver/app/keepers

Check failure on line 371 in app/keepers/keepers.go

View workflow job for this annotation

GitHub Actions / lint

comment-spacings: no space between comment delimiter and comment text (revive)
//imports github.com/quicksilver-zone/quicksilver/x/airdrop/keeper

Check failure on line 372 in app/keepers/keepers.go

View workflow job for this annotation

GitHub Actions / lint

comment-spacings: no space between comment delimiter and comment text (revive)
//imports github.com/quicksilver-zone/quicksilver/third-party-chains/osmosis-types

Check failure on line 373 in app/keepers/keepers.go

View workflow job for this annotation

GitHub Actions / lint

comment-spacings: no space between comment delimiter and comment text (revive)
//imports github.com/quicksilver-zone/quicksilver/x/claimsmanager/types

Check failure on line 374 in app/keepers/keepers.go

View workflow job for this annotation

GitHub Actions / lint

comment-spacings: no space between comment delimiter and comment text (revive)
//imports github.com/quicksilver-zone/quicksilver/x/interchainstaking/types

Check failure on line 375 in app/keepers/keepers.go

View workflow job for this annotation

GitHub Actions / lint

comment-spacings: no space between comment delimiter and comment text (revive)
//imports github.com/quicksilver-zone/quicksilver/x/claimsmanager/types
appKeepers.ClaimsManagerKeeper = claimsmanagerkeeper.NewKeeper(
appCodec,
appKeepers.keys[claimsmanagertypes.StoreKey],
appKeepers.IBCKeeper,
appKeepers.GetSubspace(claimsmanagertypes.ModuleName),
&appKeepers.InterchainQueryKeeper,
proofOpsFn,
selfProofOpsFn,
)

// claimsmanagerModule := claimsmanager.NewAppModule(appCodec, appKeepers.ClaimsManagerKeeper)
Expand Down
8 changes: 4 additions & 4 deletions proto/buf.gen.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ plugins:
- plugins=grpc,Mgoogle/protobuf/any.proto=github.com/cosmos/cosmos-sdk/codec/types,
- name: grpc-gateway
out: ..
- name: swagger
out: ../tmp-swagger-gen
opt:
- simple_operation_ids=true
# - name: swagger
# out: ../tmp-swagger-gen
# opt:
# - simple_operation_ids=true
48 changes: 48 additions & 0 deletions proto/quicksilver/claimsmanager/v1/claimsmanager.proto
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package quicksilver.claimsmanager.v1;

import "cosmos_proto/cosmos.proto";
import "gogoproto/gogo.proto";
import "google/protobuf/timestamp.proto";
import "tendermint/crypto/proof.proto";

option go_package = "github.com/quicksilver-zone/quicksilver/x/claimsmanager/types";
Expand All @@ -24,8 +25,20 @@ enum ClaimType {
message Params {
option (gogoproto.goproto_getters) = false;
option (gogoproto.goproto_stringer) = false;

bool claims_enabled = 1;
}

message ClaimableEvent {
string event_module = 1; // module name doing the claim, “govbyproxy”, “participationrewards”, “airdrop” (types.ModuleName)
string event_name = 2; // “epoch”, “proposal/cosmoshub-4/764”, “airdrop/cosmoshub-4” // todo set as id
map<string, int64> heights = 3; // heights across each chain for this event - when initialised create with the chainID and 0, for each relevant zone. For all zones, use all zones we have a connectionData for; airdrop proofs will require _latest_ (pool contents, etc.) to be submitted by the user.
google.protobuf.Timestamp max_claim_time = 4 [(gogoproto.stdtime) = true, (gogoproto.nullable) = false]; // when can we claim until? (Proposal end vote time, next epoch boundary, airdrop end)
}

// trigger self consensus state on every claimable event
// icq query fired off every time

// Claim define the users claim for holding assets within a given zone.
message Claim {
option (gogoproto.goproto_getters) = false;
Expand Down Expand Up @@ -53,3 +66,38 @@ message Proof {
int64 height = 4 [json_name = "height"];
string proof_type = 5 [json_name = "proof_type"];
}

message KeyedProtocolData {
string key = 1;
ProtocolData protocol_data = 2;
}

// Protocol Data is an arbitrary data type held against a given zone for the
// determination of rewards.
message ProtocolData {
string type = 1;
bytes data = 2 [(gogoproto.casttype) = "encoding/json.RawMessage"];
}

enum ProtocolDataType {
option (gogoproto.goproto_enum_prefix) = false;

// Undefined action (per protobuf spec)
ProtocolDataTypeUndefined = 0;
ProtocolDataTypeConnection = 1;
ProtocolDataTypeOsmosisParams = 2;
ProtocolDataTypeLiquidToken = 3;
ProtocolDataTypeOsmosisPool = 4;
ProtocolDataTypeCrescentPool = 5 [deprecated = true];
ProtocolDataTypeSifchainPool = 6 [deprecated = true];
ProtocolDataTypeUmeeParams = 7;
ProtocolDataTypeUmeeReserves = 8;
ProtocolDataTypeUmeeInterestScalar = 9;
ProtocolDataTypeUmeeTotalBorrows = 10;
ProtocolDataTypeUmeeUTokenSupply = 11;
ProtocolDataTypeUmeeLeverageModuleBalance = 12;
ProtocolDataTypeCrescentParams = 13 [deprecated = true];
ProtocolDataTypeCrescentReserveAddressBalance = 14 [deprecated = true];
ProtocolDataTypeCrescentPoolCoinSupply = 15 [deprecated = true];
ProtocolDataTypeOsmosisCLPool = 16;
}
54 changes: 53 additions & 1 deletion proto/quicksilver/claimsmanager/v1/messages.proto
Original file line number Diff line number Diff line change
@@ -1,7 +1,59 @@
syntax = "proto3";
package quicksilver.claimsmanager.v1;

import "quicksilver/claimsmanager/v1/claimsmanager.proto";
import "cosmos_proto/cosmos.proto";
import "gogoproto/gogo.proto";
import "google/api/annotations.proto";

option go_package = "github.com/quicksilver-zone/quicksilver/x/claimsmanager/types";

// Msg defines the claimsmanager Msg service.
service Msg {}
service Msg {
rpc SubmitClaim(MsgSubmitClaim) returns (MsgSubmitClaimResponse) {
option (google.api.http) = {
post: "/quicksilver/tx/v1/claimsmanager/claim"
body: "*"
};
}
rpc SubmitClaimableEvent(MsgSubmitClaimableEventClaim) returns (MsgSubmitClaimableEventClaimResponse) {
option (google.api.http) = {
post: "/quicksilver/tx/v1/claimsmanager/claimableEvent"
body: "*"
};
}
}

// MsgSubmitClaim represents a message type for submitting a
// claim regarding the given zone (chain).
message MsgSubmitClaim {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;

string user_address = 1 [
json_name = "user_address",
(cosmos_proto.scalar) = "cosmos.AddressString"
];
string zone = 2 [json_name = "zone"];
string src_zone = 3 [json_name = "src_zone"];
quicksilver.claimsmanager.v1.ClaimType claim_type = 4 [json_name = "claim_type"];
repeated quicksilver.claimsmanager.v1.Proof proofs = 5 [json_name = "proofs"];
}

// MsgSubmitClaimResponse defines the MsgSubmitClaim response type.
message MsgSubmitClaimResponse {}

message MsgSubmitClaimableEventClaim {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not needed. Will get rid of it later.

option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;

string user_address = 1 [
json_name = "user_address",
(cosmos_proto.scalar) = "cosmos.AddressString"
];
string event_module = 3 [json_name = "event_module"];
string event_name = 4 [json_name = "event_name"];
repeated quicksilver.claimsmanager.v1.Proof proofs = 5 [json_name = "proofs"];
}

message MsgSubmitClaimableEventClaimResponse {}
4 changes: 4 additions & 0 deletions proto/quicksilver/claimsmanager/v1/query.proto
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,7 @@ message QueryClaimsResponse {
repeated Claim claims = 1 [(gogoproto.nullable) = false];
cosmos.base.query.v1beta1.PageResponse pagination = 2;
}


// return all the height for each chain for each claimable event
// return latest event of each module
129 changes: 129 additions & 0 deletions x/claimsmanager/keeper/callbacks.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
package keeper

import (
"encoding/json"
"errors"
"fmt"

"github.com/cosmos/cosmos-sdk/client/grpc/tmservice"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/quicksilver-zone/quicksilver/x/claimsmanager/types"
icqtypes "github.com/quicksilver-zone/quicksilver/x/interchainquery/types"
)

const (
ValidatorSelectionRewardsCallbackID = "validatorselectionrewards"
OsmosisPoolUpdateCallbackID = "osmosispoolupdate"
OsmosisClPoolUpdateCallbackID = "osmosisclpoolupdate"
SetEpochBlockCallbackID = "epochblock"
UmeeReservesUpdateCallbackID = "umeereservesupdatecallback"
UmeeTotalBorrowsUpdateCallbackID = "umeetotalborrowsupdatecallback"
UmeeInterestScalarUpdateCallbackID = "umeeinterestscalarupdatecallback"
UmeeUTokenSupplyUpdateCallbackID = "umeeutokensupplyupdatecallback"
UmeeLeverageModuleBalanceUpdateCallbackID = "umeeleveragemodulebalanceupdatecallback"
)

type Callback func(sdk.Context, *Keeper, []byte, icqtypes.Query) error

type Callbacks struct {
k *Keeper
callbacks map[string]Callback
}

var _ icqtypes.QueryCallbacks = Callbacks{}

func (k *Keeper) CallbackHandler() Callbacks {
return Callbacks{k, make(map[string]Callback)}
}

// Call calls callback handler.
func (c Callbacks) Call(ctx sdk.Context, id string, args []byte, query icqtypes.Query) error {
if !c.Has(id) {
return fmt.Errorf("callback %s not found", id)
}
return c.callbacks[id](ctx, c.k, args, query)
}

func (c Callbacks) Has(id string) bool {
_, found := c.callbacks[id]
return found
}

func (c Callbacks) AddCallback(id string, fn interface{}) icqtypes.QueryCallbacks {
c.callbacks[id], _ = fn.(Callback)
return c
}

func (c Callbacks) RegisterCallbacks() icqtypes.QueryCallbacks {
a := c.AddCallback(SetEpochBlockCallbackID, Callback(SetEpochBlockCallback))

return a.(Callbacks)
}

// SetEpochBlockCallback records the block height of the registered zone at the epoch boundary.
func SetEpochBlockCallback(ctx sdk.Context, k *Keeper, args []byte, query icqtypes.Query) error {
k.Logger(ctx).Debug("epoch callback called")
data, connectionData, err := GetAndUnmarshalProtocolData[*types.ConnectionProtocolData](ctx, k, query.ChainId, types.ProtocolDataTypeConnection)
if err != nil {
return err
}

// block response is never expected to be nil
if len(args) == 0 {
return errors.New("attempted to unmarshal zero length byte slice (1)")
}

blockResponse := tmservice.GetLatestBlockResponse{}
err = k.cdc.Unmarshal(args, &blockResponse)
if err != nil {
return err
}
k.Logger(ctx).Debug("got block response", "block", blockResponse)

if blockResponse.SdkBlock == nil {
// v0.45 and below
// nolint:staticcheck // SA1019 ignore this!
connectionData.LastEpoch = blockResponse.Block.Header.Height
} else {
// v0.46 and above
connectionData.LastEpoch = blockResponse.SdkBlock.Header.Height
}

// todo update claimable events with all the heights collected here
k.IteratePrefixedClaimableEvent(ctx, func(index int64, key []byte, data types.ClaimableEvent) (stop bool) {
if ctx.BlockHeader().Time.Before(data.MaxClaimTime) {
// Update the heights for each claimable event
data.Heights[query.ChainId] = connectionData.LastEpoch // Update the height for the current chain

// Save the updated claimable event back to the store
if err = k.SetClaimableEvent(ctx, &data); err != nil {
k.Logger(ctx).Error("Failed to update claimable event", "event", data.EventName, "error", err)
}
return false // Continue iterating till all events have updated the chain height
}
return false
})

heightInBytes := sdk.Uint64ToBigEndian(uint64(connectionData.LastEpoch)) //nolint:gosec
// trigger a client update at the epoch boundary
k.IcqKeeper.MakeRequest(
ctx,
query.ConnectionId,
query.ChainId,
"ibc.ClientUpdate",
heightInBytes,
sdk.NewInt(-1),
types.ModuleName,
"",
0,
)

k.Logger(ctx).Debug("emitted client update", "height", connectionData.LastEpoch)

data.Data, err = json.Marshal(connectionData)
if err != nil {
return err
}
k.SetProtocolData(ctx, connectionData.GenerateKey(), &data)
return nil
}
92 changes: 92 additions & 0 deletions x/claimsmanager/keeper/claimable_event.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package keeper

import (
"fmt"

"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/quicksilver-zone/quicksilver/x/claimsmanager/types"
epochstypes "github.com/quicksilver-zone/quicksilver/x/epochs/types"
participationrewardstypes "github.com/quicksilver-zone/quicksilver/x/participationrewards/types"
)

func (k *Keeper) SetClaimableEvent(ctx sdk.Context, claimableEvent *types.ClaimableEvent) error {
if claimableEvent.MaxClaimTime.Before(ctx.BlockHeader().Time) {
return fmt.Errorf("max time cannot be less than current block time")
}

// todo : 1. call the store consensus state here after each call
// this might include callbacks etc
switch claimableEvent.EventName {
case epochstypes.ModuleName:
if err := k.StoreSelfConsensusState(ctx, "epoch"); err != nil {
return err
}
case participationrewardstypes.ModuleName:
// zones: can get it from protocol data
default:
}

var listOfChains []string
k.IteratePrefixedProtocolDatas(ctx, types.GetPrefixProtocolDataKey(types.ProtocolDataTypeConnection), func(index int64, _ []byte, data types.ProtocolData) (stop bool) {
iConnectionData, err := types.UnmarshalProtocolData(types.ProtocolDataTypeConnection, data.Data)
if err != nil {
k.Logger(ctx).Error("Error unmarshalling protocol data")
}
connectionData, _ := iConnectionData.(*types.ConnectionProtocolData)
listOfChains = append(listOfChains, connectionData.ChainID)
return

Check failure on line 38 in x/claimsmanager/keeper/claimable_event.go

View workflow job for this annotation

GitHub Actions / lint

bare-return: avoid using bare returns, please add return expressions (revive)
})

for _, chainID := range listOfChains {
claimableEvent.Heights[chainID] = 0
}

//2. store rest of the data as is for the claimable event

Check failure on line 45 in x/claimsmanager/keeper/claimable_event.go

View workflow job for this annotation

GitHub Actions / lint

commentFormatting: put a space between `//` and comment text (gocritic)
store := prefix.NewStore(ctx.KVStore(k.storeKey), nil)
bz := k.cdc.MustMarshal(claimableEvent)
store.Set(types.GetKeyClaimableEvent(claimableEvent.EventModule, claimableEvent.EventName), bz)
return nil
}

func (k *Keeper) GetClaimableEvent(ctx sdk.Context, eventModule, eventName string) (types.ClaimableEvent, bool) {
data := types.ClaimableEvent{}
store := prefix.NewStore(ctx.KVStore(k.storeKey), nil)
key := types.GetGenericKeyClaimableEvent(eventModule, eventName)
bz := store.Get(key)
if len(bz) == 0 {
return data, false
}

k.cdc.MustUnmarshal(bz, &data)
return data, true
}

func (k *Keeper) IteratePrefixedClaimableEvent(ctx sdk.Context, fn func(index int64, key []byte, data types.ClaimableEvent) (stop bool)) {
if fn == nil {
return
}

store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, types.KeyPrefixClaimableEvent)
defer iterator.Close()

i := int64(0)
for ; iterator.Valid(); iterator.Next() {
data := types.ClaimableEvent{}
k.cdc.MustUnmarshal(iterator.Value(), &data)
stop := fn(i, iterator.Key(), data)
if stop {
break
}
i++

}
}

func (k *Keeper) DeleteClaimableEvent(ctx sdk.Context, eventModule, eventName string) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), nil)
key := types.GetGenericKeyClaimableEvent(eventModule, eventName)

store.Delete(key)
}
Loading
Loading