Skip to content

Commit

Permalink
feat: implement nft module msg server (#10074)
Browse files Browse the repository at this point in the history
<!--
The default pull request template is for types feat, fix, or refactor.
For other templates, add one of the following parameters to the url:
- template=docs.md
- template=other.md
-->

## Description

MsgServer implementation and corresponding keeper methods, refer #9826

<!-- Add a description of the changes that this PR introduces and the files that
are the most critical to review. -->

---

### Author Checklist

*All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.*

I have...

- [ ] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title
- [ ] added `!` to the type prefix if API or client breaking change
- [ ] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting))
- [ ] provided a link to the relevant issue or specification
- [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules)
- [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing)
- [ ] added a changelog entry to `CHANGELOG.md`
- [ ] included comments for [documenting Go code](https://blog.golang.org/godoc)
- [ ] updated the relevant documentation or specification
- [ ] reviewed "Files changed" and left comments if necessary
- [ ] confirmed all CI checks have passed

### Reviewers Checklist

*All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.*

I have...

- [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title
- [ ] confirmed `!` in the type prefix if API or client breaking change
- [ ] confirmed all author checklist items have been addressed 
- [ ] reviewed state machine logic
- [ ] reviewed API design and naming
- [ ] reviewed documentation is accurate
- [ ] reviewed tests and test coverage
- [ ] manually tested (if applicable)
  • Loading branch information
Zhiqiang Zhang committed Oct 27, 2021
1 parent 0a3660d commit 1d1fcc9
Show file tree
Hide file tree
Showing 20 changed files with 1,175 additions and 21 deletions.
12 changes: 11 additions & 1 deletion docs/architecture/adr-043-nft-module.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,13 @@ DRAFT

## Abstract

This ADR defines the `x/nft` module which is a generic implementation of NFTs, roughly "compatible" with ERC721.
This ADR defines the `x/nft` module which is a generic implementation of NFTs, roughly "compatible" with ERC721. **Applications using the `x/nft` module must implement the following functions**:

- `MsgNewClass` - Receive the user's request to create a class, and call the `NewClass` of the `x/nft` module.
- `MsgUpdateClass` - Receive the user's request to update a class, and call the `UpdateClass` of the `x/nft` module.
- `MsgMintNFT` - Receive the user's request to mint a nft, and call the `MintNFT` of the `x/nft` module.
- `BurnNFT` - Receive the user's request to burn a nft, and call the `BurnNFT` of the `x/nft` module.
- `UpdateNFT` - Receive the user's request to update a nft, and call the `UpdateNFT` of the `x/nft` module.

## Context

Expand Down Expand Up @@ -55,6 +61,7 @@ message Class {
string symbol = 3;
string description = 4;
string uri = 5;
string uri_hash = 6;
}
```

Expand All @@ -63,6 +70,7 @@ message Class {
- `symbol` is the symbol usually shown on exchanges for the NFT class; _optional_
- `description` is a detailed description of the NFT class; _optional_
- `uri` is a URL pointing to an off-chain JSON file that contains metadata about this NFT class ([OpenSea example](https://docs.opensea.io/docs/contract-level-metadata)); _optional_
- `uri_hash` is a hash of the `uri`; _optional_

#### NFT

Expand All @@ -73,6 +81,7 @@ message NFT {
string class_id = 1;
string id = 2;
string uri = 3;
string uri_hash = 4;
google.protobuf.Any data = 10;
}
```
Expand All @@ -83,6 +92,7 @@ message NFT {
{class_id}/{id} --> NFT (bytes)
```
- `uri` is a URL pointing to an off-chain JSON file that contains metadata about this NFT (Ref: [ERC721 standard and OpenSea extension](https://docs.opensea.io/docs/metadata-standards)); _required_
- `uri_hash` is a hash of the `uri`;
- `data` is a field that CAN be used by composing modules to specify additional properties for the NFT; _optional_

This ADR doesn't specify values that `data` can take; however, best practices recommend upper-level NFT modules clearly specify their contents. Although the value of this field doesn't provide the additional context required to manage NFT records, which means that the field can technically be removed from the specification, the field's existence allows basic informational/UI functionality.
Expand Down
12 changes: 6 additions & 6 deletions docs/core/proto-docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -7290,11 +7290,11 @@ Class defines the class of the nft type.
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| `id` | [string](#string) | | id defines the unique identifier of the NFT classification, similar to the contract address of ERC721 |
| `name` | [string](#string) | | name defines the human-readable name of the NFT classification |
| `symbol` | [string](#string) | | symbol is an abbreviated name for nft classification |
| `description` | [string](#string) | | description is a brief description of nft classification |
| `uri` | [string](#string) | | uri is a URI may point to a JSON file that conforms to the nft classification Metadata JSON Schema. |
| `uri_hash` | [string](#string) | | uri_hash is a hash of the document pointed to uri |
| `name` | [string](#string) | | name defines the human-readable name of the NFT classification,optional |
| `symbol` | [string](#string) | | symbol is an abbreviated name for nft classification,optional |
| `description` | [string](#string) | | description is a brief description of nft classification,optional |
| `uri` | [string](#string) | | uri is a URI may point to a JSON file that conforms to the nft classification Metadata JSON Schema.optional |
| `uri_hash` | [string](#string) | | uri_hash is a hash of the document pointed to uri,optional |



Expand All @@ -7313,7 +7313,7 @@ NFT defines the NFT.
| `id` | [string](#string) | | id defines the unique identification of NFT |
| `uri` | [string](#string) | | uri defines NFT's metadata storage address outside the chain |
| `uri_hash` | [string](#string) | | uri_hash is a hash of the document pointed to uri |
| `data` | [google.protobuf.Any](#google.protobuf.Any) | | data is the metadata of the NFT |
| `data` | [google.protobuf.Any](#google.protobuf.Any) | | data is the metadata of the NFT,optional |



Expand Down
12 changes: 6 additions & 6 deletions proto/cosmos/nft/v1beta1/nft.proto
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,19 @@ message Class {
// id defines the unique identifier of the NFT classification, similar to the contract address of ERC721
string id = 1;

// name defines the human-readable name of the NFT classification
// name defines the human-readable name of the NFT classification,optional
string name = 2;

// symbol is an abbreviated name for nft classification
// symbol is an abbreviated name for nft classification,optional
string symbol = 3;

// description is a brief description of nft classification
// description is a brief description of nft classification,optional
string description = 4;

// uri is a URI may point to a JSON file that conforms to the nft classification Metadata JSON Schema.
// uri is a URI may point to a JSON file that conforms to the nft classification Metadata JSON Schema.optional
string uri = 5;

// uri_hash is a hash of the document pointed to uri
// uri_hash is a hash of the document pointed to uri,optional
string uri_hash = 6;
}

Expand All @@ -40,6 +40,6 @@ message NFT {
// uri_hash is a hash of the document pointed to uri
string uri_hash = 4;

// data is the metadata of the NFT
// data is the metadata of the NFT,optional
google.protobuf.Any data = 10;
}
12 changes: 10 additions & 2 deletions simapp/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ import (
"github.com/cosmos/cosmos-sdk/x/mint"
mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
"github.com/cosmos/cosmos-sdk/x/nft"
nftkeeper "github.com/cosmos/cosmos-sdk/x/nft/keeper"
nftmodule "github.com/cosmos/cosmos-sdk/x/nft/module"
"github.com/cosmos/cosmos-sdk/x/params"
paramsclient "github.com/cosmos/cosmos-sdk/x/params/client"
paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper"
Expand Down Expand Up @@ -117,6 +120,7 @@ var (
evidence.AppModuleBasic{},
authzmodule.AppModuleBasic{},
vesting.AppModuleBasic{},
nftmodule.AppModuleBasic{},
)

// module account permissions
Expand All @@ -127,6 +131,7 @@ var (
stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking},
stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking},
govtypes.ModuleName: {authtypes.Burner},
nft.ModuleName: nil,
}
)

Expand Down Expand Up @@ -168,6 +173,7 @@ type SimApp struct {
AuthzKeeper authzkeeper.Keeper
EvidenceKeeper evidencekeeper.Keeper
FeeGrantKeeper feegrantkeeper.Keeper
NFTKeeper nftkeeper.Keeper

// the module manager
mm *module.Manager
Expand Down Expand Up @@ -209,7 +215,7 @@ func NewSimApp(
minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey,
govtypes.StoreKey, paramstypes.StoreKey, upgradetypes.StoreKey, feegrant.StoreKey,
evidencetypes.StoreKey, capabilitytypes.StoreKey,
authzkeeper.StoreKey,
authzkeeper.StoreKey, nftkeeper.StoreKey,
)
tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey)
// NOTE: The testingkey is just mounted for testing purposes. Actual applications should
Expand Down Expand Up @@ -297,6 +303,7 @@ func NewSimApp(
// register the governance hooks
),
)
app.NFTKeeper = nftkeeper.NewKeeper(keys[nftkeeper.StoreKey], appCodec, app.AccountKeeper, app.BankKeeper)

// create evidence keeper with router
evidenceKeeper := evidencekeeper.NewKeeper(
Expand Down Expand Up @@ -333,6 +340,7 @@ func NewSimApp(
evidence.NewAppModule(app.EvidenceKeeper),
params.NewAppModule(app.ParamsKeeper),
authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry),
nftmodule.NewAppModule(appCodec, app.NFTKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry),
)

// During begin block slashing happens after distr.BeginBlocker so that
Expand All @@ -355,7 +363,7 @@ func NewSimApp(
capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, distrtypes.ModuleName, stakingtypes.ModuleName,
slashingtypes.ModuleName, govtypes.ModuleName, minttypes.ModuleName, crisistypes.ModuleName,
genutiltypes.ModuleName, evidencetypes.ModuleName, authz.ModuleName,
feegrant.ModuleName,
feegrant.ModuleName, nft.ModuleName,
)

app.mm.RegisterInvariants(&app.CrisisKeeper)
Expand Down
14 changes: 14 additions & 0 deletions x/nft/codec.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package nft

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

func RegisterInterfaces(registry types.InterfaceRegistry) {
registry.RegisterImplementations((*sdk.Msg)(nil),
&MsgSend{},
)
msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc)
}
15 changes: 15 additions & 0 deletions x/nft/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package nft

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

// x/nft module sentinel errors
var (
ErrInvalidNFT = sdkerrors.Register(ModuleName, 2, "invalid nft")
ErrClassExists = sdkerrors.Register(ModuleName, 3, "nft class already exist")
ErrClassNotExists = sdkerrors.Register(ModuleName, 4, "nft class does not exist")
ErrNFTExists = sdkerrors.Register(ModuleName, 5, "nft already exist")
ErrNFTNotExists = sdkerrors.Register(ModuleName, 6, "nft does not exist")
ErrInvalidID = sdkerrors.Register(ModuleName, 7, "invalid id")
)
18 changes: 18 additions & 0 deletions x/nft/expected_keepers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package nft

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

// BankKeeper defines the contract needed to be fulfilled for banking and supply
// dependencies.
type BankKeeper interface {
SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins
}

// AccountKeeper defines the contract required for account APIs.
type AccountKeeper interface {
GetModuleAddress(name string) sdk.AccAddress
GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI
}
30 changes: 30 additions & 0 deletions x/nft/genesis.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package nft

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

// ValidateGenesis check the given genesis state has no integrity issues
func ValidateGenesis(data GenesisState) error {
for _, class := range data.Classes {
if err := ValidateClassID(class.Id); err != nil {
return err
}
}
for _, entry := range data.Entries {
for _, nft := range entry.Nfts {
if err := ValidateNFTID(nft.Id); err != nil {
return err
}
if _, err := sdk.AccAddressFromBech32(entry.Owner); err != nil {
return err
}
}
}
return nil
}

// DefaultGenesisState - Return a default genesis state
func DefaultGenesisState() *GenesisState {
return &GenesisState{}
}
67 changes: 67 additions & 0 deletions x/nft/keeper/class.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package keeper

import (
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/nft"
)

// SaveClass defines a method for creating a new nft class
func (k Keeper) SaveClass(ctx sdk.Context, class nft.Class) error {
if k.HasClass(ctx, class.Id) {
return sdkerrors.Wrap(nft.ErrClassExists, class.Id)
}
bz, err := k.cdc.Marshal(&class)
if err != nil {
return sdkerrors.Wrap(err, "Marshal nft.Class failed")
}
store := ctx.KVStore(k.storeKey)
store.Set(classStoreKey(class.Id), bz)
return nil
}

// UpdateClass defines a method for updating a exist nft class
func (k Keeper) UpdateClass(ctx sdk.Context, class nft.Class) error {
if !k.HasClass(ctx, class.Id) {
return sdkerrors.Wrap(nft.ErrClassNotExists, class.Id)
}
bz, err := k.cdc.Marshal(&class)
if err != nil {
return sdkerrors.Wrap(err, "Marshal nft.Class failed")
}
store := ctx.KVStore(k.storeKey)
store.Set(classStoreKey(class.Id), bz)
return nil
}

// GetClass defines a method for returning the class information of the specified id
func (k Keeper) GetClass(ctx sdk.Context, classID string) (nft.Class, bool) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(classStoreKey(classID))

var class nft.Class
if len(bz) == 0 {
return class, false
}
k.cdc.MustUnmarshal(bz, &class)
return class, true
}

// GetClasses defines a method for returning all classes information
func (k Keeper) GetClasses(ctx sdk.Context) (classes []*nft.Class) {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, ClassKey)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var class nft.Class
k.cdc.MustUnmarshal(iterator.Value(), &class)
classes = append(classes, &class)
}
return
}

// HasClass determines whether the specified classID exist
func (k Keeper) HasClass(ctx sdk.Context, classID string) bool {
store := ctx.KVStore(k.storeKey)
return store.Has(classStoreKey(classID))
}
65 changes: 65 additions & 0 deletions x/nft/keeper/genesis.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package keeper

import (
"sort"

sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/nft"
)

// InitGenesis new nft genesis
func (k Keeper) InitGenesis(ctx sdk.Context, data *nft.GenesisState) {
for _, class := range data.Classes {
if err := k.SaveClass(ctx, *class); err != nil {
panic(err)
}

}
for _, entry := range data.Entries {
for _, nft := range entry.Nfts {
owner, err := sdk.AccAddressFromBech32(entry.Owner)
if err != nil {
panic(err)
}

if err := k.Mint(ctx, *nft, owner); err != nil {
panic(err)
}
}
}
}

// ExportGenesis returns a GenesisState for a given context.
func (k Keeper) ExportGenesis(ctx sdk.Context) *nft.GenesisState {
classes := k.GetClasses(ctx)
nftMap := make(map[string][]*nft.NFT)
for _, class := range classes {
nfts := k.GetNFTsOfClass(ctx, class.Id)
for i, n := range nfts {
owner := k.GetOwner(ctx, n.ClassId, n.Id)
nftArr, ok := nftMap[owner.String()]
if !ok {
nftArr = make([]*nft.NFT, 0)
}
nftMap[owner.String()] = append(nftArr, &nfts[i])
}
}

owners := make([]string, 0, len(nftMap))
for owner := range nftMap {
owners = append(owners, owner)
}
sort.Strings(owners)

entries := make([]*nft.Entry, 0, len(nftMap))
for _, owner := range owners {
entries = append(entries, &nft.Entry{
Owner: owner,
Nfts: nftMap[owner],
})
}
return &nft.GenesisState{
Classes: classes,
Entries: entries,
}
}
Loading

0 comments on commit 1d1fcc9

Please sign in to comment.