Skip to content

Commit

Permalink
Add order sequence to DEX extension call. (#1044)
Browse files Browse the repository at this point in the history
  • Loading branch information
dzmitryhil authored Dec 9, 2024
1 parent 6a1b506 commit 43cac5a
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 46 deletions.
34 changes: 12 additions & 22 deletions x/asset/ft/keeper/test-contracts/asset-extension/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,18 @@ use crate::msg::{
use crate::state::{DENOM, EXTRA_DATA};
use coreum_wasm_sdk::deprecated::core::{CoreumMsg, CoreumResult};
use coreum_wasm_sdk::types::coreum::asset::ft::v1::{
MsgBurn, MsgMint, QueryFrozenBalanceRequest, QueryFrozenBalanceResponse, QueryTokenRequest,
QueryTokenResponse, Token,
MsgBurn, MsgMint, QueryTokenRequest, QueryTokenResponse, Token,
};
use coreum_wasm_sdk::types::cosmos::bank::v1beta1::{
MsgSend, QueryBalanceRequest, QueryBalanceResponse,
MsgSend,
};
use coreum_wasm_sdk::types::cosmos::base::v1beta1::Coin;
use cosmwasm_std::{entry_point, to_json_binary, CosmosMsg, StdError};
use cosmwasm_std::{Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, Uint128};
use cw2::set_contract_version;
use std::ops::Div;
use std::string::ToString;
use cosmwasm_schema::schemars::_serde_json::to_string;

// version info for migration info
const CONTRACT_NAME: &str = env!("CARGO_PKG_NAME");
Expand Down Expand Up @@ -189,7 +189,15 @@ pub fn sudo_extension_place_order(
{
return Err(ContractError::DEXOrderPlacementError {});
}
Ok(Response::new().add_attribute("method", "extension_place_order"))

let order_data = to_string(&order).
map_err(|_| ContractError::Std(StdError::generic_err("failed to serialize order to json string")))?;

Ok(
Response::new()
.add_attribute("method", "extension_place_order")
.add_attribute("order_data", order_data)
)
}

#[cfg_attr(not(feature = "library"), entry_point)]
Expand Down Expand Up @@ -376,24 +384,6 @@ fn assert_burn_rate(
.add_message(CosmosMsg::Any(burn_message.to_any())))
}

fn query_frozen_balance(deps: Deps, account: &str, denom: &str) -> StdResult<Coin> {
let request = QueryFrozenBalanceRequest {
account: account.to_string(),
denom: denom.to_string(),
};
let frozen_balance: QueryFrozenBalanceResponse = request.query(&deps.querier)?;
Ok(frozen_balance.balance.unwrap_or_default())
}

fn query_bank_balance(deps: Deps, account: &str, denom: &str) -> StdResult<Coin> {
let request = QueryBalanceRequest {
address: account.to_string(),
denom: denom.to_string(),
};
let bank_balance: QueryBalanceResponse = request.query(&deps.querier)?;
Ok(bank_balance.balance.unwrap_or_default())
}

fn query_token(deps: Deps, denom: &str) -> StdResult<Token> {
let request = QueryTokenRequest {
denom: denom.to_string(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub struct DEXOrder {
#[serde(rename = "type")]
pub order_type: String,
pub id: String,
pub sequence: u64,
pub base_denom: String,
pub quote_denom: String,
pub price: Option<String>,
Expand Down
1 change: 1 addition & 0 deletions x/asset/ft/types/dex.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ type DEXOrder struct {
Creator sdk.AccAddress `json:"creator"`
Type string `json:"type"`
ID string `json:"id"`
Sequence uint64 `json:"sequence"`
BaseDenom string `json:"base_denom"`
QuoteDenom string `json:"quote_denom"`
Price *string `json:"price,omitempty"` // might be nil
Expand Down
61 changes: 37 additions & 24 deletions x/dex/keeper/keeper_ft_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package keeper_test

import (
"encoding/json"
"fmt"
"testing"
"time"
Expand All @@ -18,14 +19,19 @@ import (
"github.com/samber/lo"
"github.com/stretchr/testify/require"

"github.com/CoreumFoundation/coreum/v5/testutil/event"
"github.com/CoreumFoundation/coreum/v5/testutil/simapp"
testcontracts "github.com/CoreumFoundation/coreum/v5/x/asset/ft/keeper/test-contracts"
assetfttypes "github.com/CoreumFoundation/coreum/v5/x/asset/ft/types"
"github.com/CoreumFoundation/coreum/v5/x/dex/types"
)

var (
const (
ExtensionOrderDataWASMAttribute = "order_data"
IDDEXOrderSuffixTrigger = "blocked"
)

var (
AmountDEXExpectToSpendTrigger = sdkmath.NewInt(103)
AmountDEXExpectToReceiveTrigger = sdkmath.NewInt(104)
)
Expand Down Expand Up @@ -84,7 +90,7 @@ func TestKeeper_PlaceOrderWithExtension(t *testing.T) {
wantDEXErr: false,
},
{
name: "sell_dex_error_spend_amount",
name: "sell_dex_error",
order: types.Order{
Creator: func() string {
creator, _ := testApp.GenAccount(sdkCtx)
Expand All @@ -101,24 +107,6 @@ func TestKeeper_PlaceOrderWithExtension(t *testing.T) {
},
wantDEXErr: true,
},
{
name: "sell_dex_error_order_id",
order: types.Order{
Creator: func() string {
creator, _ := testApp.GenAccount(sdkCtx)
return creator.String()
}(),
Type: types.ORDER_TYPE_LIMIT,
ID: uuid.Generate().String()[:10] + IDDEXOrderSuffixTrigger,
BaseDenom: denomWithExtension,
QuoteDenom: denom2,
Price: lo.ToPtr(types.MustNewPriceFromString("1")),
Quantity: sdkmath.NewInt(10),
Side: types.SIDE_SELL,
TimeInForce: types.TIME_IN_FORCE_GTC,
},
wantDEXErr: true,
},
{
name: "buy_positive",
order: types.Order{
Expand All @@ -138,7 +126,7 @@ func TestKeeper_PlaceOrderWithExtension(t *testing.T) {
wantDEXErr: false,
},
{
name: "buy_dex_error_receive_amount",
name: "buy_dex_error",
order: types.Order{
Creator: func() string {
creator, _ := testApp.GenAccount(sdkCtx)
Expand All @@ -164,13 +152,38 @@ func TestKeeper_PlaceOrderWithExtension(t *testing.T) {
testApp.MintAndSendCoin(t, sdkCtx, creator, sdk.NewCoins(lockedBalance))
fundOrderReserve(t, testApp, sdkCtx, creator)
if !tt.wantDEXErr {
sdkCtx = sdkCtx.WithEventManager(sdk.NewEventManager())
require.NoError(t, testApp.DEXKeeper.PlaceOrder(sdkCtx, tt.order))

// decode wasm events
orderStr, err := event.FindStringEventAttribute(
sdkCtx.EventManager().Events().ToABCIEvents(),
wasmtypes.WasmModuleEventType,
ExtensionOrderDataWASMAttribute,
)
require.NoError(t, err)

extensionOrderData := assetfttypes.DEXOrder{}
require.NoError(t, json.Unmarshal([]byte(orderStr), &extensionOrderData))

order, err := testApp.DEXKeeper.GetOrderByAddressAndID(sdkCtx, creator, tt.order.ID)
require.NoError(t, err)

require.Equal(t, assetfttypes.DEXOrder{
Creator: sdk.MustAccAddressFromBech32(order.Creator),
Type: order.Type.String(),
ID: order.ID,
Sequence: order.Sequence,
BaseDenom: order.BaseDenom,
QuoteDenom: order.QuoteDenom,
Price: lo.ToPtr(order.Price.String()),
Quantity: order.Quantity,
Side: order.Side.String(),
}, extensionOrderData)
} else {
err := testApp.DEXKeeper.PlaceOrder(sdkCtx, tt.order)
require.ErrorIs(t, err, assetfttypes.ErrExtensionCallFailed)
require.ErrorContains(
t,
err,
testApp.DEXKeeper.PlaceOrder(simapp.CopyContextWithMultiStore(sdkCtx), tt.order),
"wasm error: DEX order placement is failed",
)
}
Expand Down
1 change: 1 addition & 0 deletions x/dex/keeper/keeper_matching_result.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ func NewMatchingResult(order types.Order) (*MatchingResult, error) {
Creator: takerAddress,
Type: order.Type.String(),
ID: order.ID,
Sequence: order.Sequence,
BaseDenom: order.BaseDenom,
QuoteDenom: order.QuoteDenom,
Price: orderStrPrice,
Expand Down

0 comments on commit 43cac5a

Please sign in to comment.