-
Notifications
You must be signed in to change notification settings - Fork 338
/
nft.go
75 lines (59 loc) · 2.43 KB
/
nft.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright (c) 2016-2021 Shanghai Bianjie AI Technology Inc. (licensed under the Apache License, Version 2.0)
// Modifications Copyright (c) 2021, CRO Protocol Labs ("Crypto.org") (licensed under the Apache License, Version 2.0)
package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/crypto-org-chain/chain-main/v2/x/nft/exported"
"github.com/crypto-org-chain/chain-main/v2/x/nft/types"
)
// GetNFT gets the the specified NFT
func (k Keeper) GetNFT(ctx sdk.Context, denomID, tokenID string) (nft exported.NFT, err error) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.KeyNFT(denomID, tokenID))
if bz == nil {
return nil, sdkerrors.Wrapf(types.ErrUnknownCollection, "not found NFT: %s", denomID)
}
var baseNFT types.BaseNFT
k.cdc.MustUnmarshalBinaryBare(bz, &baseNFT)
return baseNFT, nil
}
// GetNFTs returns all NFTs by the specified denom ID
func (k Keeper) GetNFTs(ctx sdk.Context, denom string) (nfts []exported.NFT) {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, types.KeyNFT(denom, ""))
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var baseNFT types.BaseNFT
k.cdc.MustUnmarshalBinaryBare(iterator.Value(), &baseNFT)
nfts = append(nfts, baseNFT)
}
return nfts
}
// IsOwner checks if the sender is the owner of the given NFT
// Return the NFT if true, an error otherwise
func (k Keeper) IsOwner(ctx sdk.Context, denomID, tokenID string, owner sdk.AccAddress) (types.BaseNFT, error) {
nft, err := k.GetNFT(ctx, denomID, tokenID)
if err != nil {
return types.BaseNFT{}, err
}
if !owner.Equals(nft.GetOwner()) {
return types.BaseNFT{}, sdkerrors.Wrapf(types.ErrUnauthorized, "%s is not the owner of %s/%s", owner.String(), denomID, tokenID)
}
return nft.(types.BaseNFT), nil
}
// HasNFT checks if the specified NFT exists
func (k Keeper) HasNFT(ctx sdk.Context, denomID, tokenID string) bool {
store := ctx.KVStore(k.storeKey)
return store.Has(types.KeyNFT(denomID, tokenID))
}
func (k Keeper) setNFT(ctx sdk.Context, denomID string, nft types.BaseNFT) {
store := ctx.KVStore(k.storeKey)
bz := k.cdc.MustMarshalBinaryBare(&nft)
store.Set(types.KeyNFT(denomID, nft.GetID()), bz)
}
// deleteNFT deletes an existing NFT from store
func (k Keeper) deleteNFT(ctx sdk.Context, denomID string, nft exported.NFT) {
store := ctx.KVStore(k.storeKey)
store.Delete(types.KeyNFT(denomID, nft.GetID()))
}