|
| 1 | +// x/nameservice/keeper/msg_server_buy_name.go |
| 2 | + |
1 | 3 | package keeper |
2 | 4 |
|
3 | 5 | import ( |
4 | 6 | "context" |
5 | 7 |
|
6 | 8 | sdk "github.com/cosmos/cosmos-sdk/types" |
| 9 | + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" |
| 10 | + |
7 | 11 | "nameservice/x/nameservice/types" |
8 | 12 | ) |
9 | 13 |
|
10 | 14 | func (k msgServer) BuyName(goCtx context.Context, msg *types.MsgBuyName) (*types.MsgBuyNameResponse, error) { |
11 | 15 | ctx := sdk.UnwrapSDKContext(goCtx) |
12 | 16 |
|
13 | | - // TODO: Handling the message |
14 | | - _ = ctx |
| 17 | + // Try getting a name from the store |
| 18 | + whois, isFound := k.GetWhois(ctx, msg.Name) |
| 19 | + |
| 20 | + // Set the price at which the name has to be bought if it didn't have an owner before |
| 21 | + minPrice := sdk.Coins{sdk.NewInt64Coin("token", 10)} |
| 22 | + |
| 23 | + // Convert price and bid strings to sdk.Coins |
| 24 | + price, _ := sdk.ParseCoinsNormalized(whois.Price) |
| 25 | + bid, _ := sdk.ParseCoinsNormalized(msg.Bid) |
| 26 | + |
| 27 | + // Convert owner and buyer address strings to sdk.AccAddress |
| 28 | + owner, _ := sdk.AccAddressFromBech32(whois.Owner) |
| 29 | + buyer, _ := sdk.AccAddressFromBech32(msg.Creator) |
| 30 | + |
| 31 | + // If a name is found in store |
| 32 | + if isFound { |
| 33 | + // If the current price is higher than the bid |
| 34 | + if price.IsAllGT(bid) { |
| 35 | + // Throw an error |
| 36 | + return nil, sdkerrors.Wrap(sdkerrors.ErrInsufficientFunds, "Bid is not high enough") |
| 37 | + } |
| 38 | + |
| 39 | + // Otherwise (when the bid is higher), send tokens from the buyer to the owner |
| 40 | + k.bankKeeper.SendCoins(ctx, buyer, owner, bid) |
| 41 | + } else { // If the name is not found in the store |
| 42 | + // If the minimum price is higher than the bid |
| 43 | + if minPrice.IsAllGT(bid) { |
| 44 | + // Throw an error |
| 45 | + return nil, sdkerrors.Wrap(sdkerrors.ErrInsufficientFunds, "Bid is less than min amount") |
| 46 | + } |
| 47 | + |
| 48 | + // Otherwise (when the bid is higher), send tokens from the buyer's account to the module's account (as a payment for the name) |
| 49 | + k.bankKeeper.SendCoinsFromAccountToModule(ctx, buyer, types.ModuleName, bid) |
| 50 | + } |
| 51 | + |
| 52 | + // Create an updated whois record |
| 53 | + newWhois := types.Whois{ |
| 54 | + Index: msg.Name, |
| 55 | + Name: msg.Name, |
| 56 | + Value: whois.Value, |
| 57 | + Price: bid.String(), |
| 58 | + Owner: buyer.String(), |
| 59 | + } |
15 | 60 |
|
| 61 | + // Write whois information to the store |
| 62 | + k.SetWhois(ctx, newWhois) |
16 | 63 | return &types.MsgBuyNameResponse{}, nil |
17 | 64 | } |
0 commit comments