Skip to content
This repository has been archived by the owner on Dec 29, 2023. It is now read-only.

Commit

Permalink
fix all the findings (#60)
Browse files Browse the repository at this point in the history
* feat: map error

* docs: create margin order update

* fix: fix mocking of the instantiate

* feat: fix test, add map handling for order and reply, change status , updated doc

* docs: add deployement instruction

* fix: optimisation of create spot orders
  • Loading branch information
politeWall authored Dec 6, 2023
1 parent f898b8c commit 16b7711
Show file tree
Hide file tree
Showing 66 changed files with 587 additions and 467 deletions.
10 changes: 5 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "trade_shield_contract"
version = "0.9.0"
version = "0.10.0"
edition = "2021"

[lib]
Expand All @@ -14,13 +14,13 @@ thiserror = "1"
schemars = "0.8.1"
cosmwasm-schema = "1.1.4"
cw-utils = "0.13"
elys-bindings = { version = "0.6.0", git = "https://github.com/elys-network/bindings", tag = "v0.6.0" }
elys-bindings = { version = "0.8.0", git = "https://github.com/elys-network/bindings", tag = "v0.8.0" }

[dev-dependencies]

cw-multi-test = "0.13.4"
serde_json = "1.0.107"
elys-bindings = { version = "0.6.0", git = "https://github.com/elys-network/bindings", tag = "v0.6.0", features = [
elys-bindings = { version = "0.8.0", git = "https://github.com/elys-network/bindings", tag = "v0.8.0", features = [
"testing",
] }
elys-bindings-test = { version = "0.6.0", git = "https://github.com/elys-network/bindings", tag = "v0.6.0" }
elys-bindings-test = { version = "0.8.0", git = "https://github.com/elys-network/bindings", tag = "v0.8.0" }
42 changes: 42 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,48 @@ To start using TradeShield, follow these steps:
4. Review the example implementations provided in the repository to understand the integration process.
5. Customize and deploy the TradeShield smart contracts according to your specific project requirements.

## Deployment Steps for Elys Network

1. Install Ignite CLI
Begin by installing the Ignite CLI tool by following the instructions provided in the [Ignite CLI documentation](https://docs.ignite.com/welcome/install).

2. Clone the Elys Repository
Clone the [Elys repository](https://github.com/elys-network/elys/releases) from GitHub and carefully follow the installation instructions provided.

3. Modify `config.yml`
Within the Elys repository, navigate to the root directory and locate the `config.yml` file. Modify the following lines:

- Change the `contract_addresses` value (line 38) to `["elys14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s3fsthx"]`.
- Modify the `broker_address` (line 439) to `"elys14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s3fsthx"`.

4. Start Ignite Node
Open a separate terminal within the Elys repository and run the command:

```sh
ignite chain serve -r
```

Optionally, use `-v` to display the node logs.

5. Download the Contract
Download the desired version of the contract from the [contract repository](https://github.com/elys-network/trade-shield-contract/releases).

6. Store Contract on Chain
Run the following command to store the contract on the chain:

```sh
elysd tx wasm store path/to/account_history_contract.wasm --from=treasury --keyring-backend=test --chain-id=elystestnet-1 --gas=auto --gas-adjustment=1.3 -y -b=sync
```

Ensure to replace `path/to/account_history_contract.wasm` with the actual path to the downloaded contract.

7. Instantiate Contract
Execute the command below to instantiate the contract on the Elys network:

```sh
elysd tx wasm instantiate 1 '{}' --from=treasury --label "Contract" --chain-id=elystestnet-1 --gas=auto --gas-adjustment=1.3 -b=sync --keyring-backend=test --no-admin -y
```

## Contributing

We welcome contributions from the community to enhance TradeShield's functionality and usability. If you would like to contribute, please follow the guidelines outlined in the `CONTRIBUTING.md` file.
Expand Down
65 changes: 48 additions & 17 deletions front_end_script/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ createSpotOrder(

```js
createSpotOrder(
[{ pool_id: 4, token_out_denom: "BTC" }, "AMM_Route_2"],
{ base_denom: "BTC", quote_denom: "ETH", rate: "0.035" },
"limit_buy",
"2.5",
Expand All @@ -49,7 +48,6 @@ createSpotOrder(
);

createSpotOrder(
null,
{ base_denom: "BTC", quote_denom: "ETH", rate: "0.035" },
"limit_buy",
"2.5",
Expand Down Expand Up @@ -78,28 +76,29 @@ cancelSpotOrder("your_order_id_here");
cancelSpotOrder("8");
```

### 3. cancelSpotOrders(pagination, order_type, owner_address)
### 3. cancelSpotOrders(order_ids, order_type, owner_address)

This function retrieves information about multiple order by querying a CosmWasm contract on the blockchain.

#### Parameters

- `order_ids` ([u64] or null): list of order ids that should be canceled
- `order_type` (OrderType or null): select the order type that should be canceled
- `owner_address` (String): select the owner of the order that should be canceled

#### Usage

```javascript
cancelSpotOrders("order_type", "owner_address", order_ids);
cancelSpotOrders("order_ids", "order_type", "order_owner");
```

#### Exemple

```js
cancelSpotOrders(
[5, 4, 6],
"limit_sell",
"elys1x5fehwug2vtkyn4vpunwkfn9zxkpxl8jg0lwuu",
[5, 4, 6]
"elys1x5fehwug2vtkyn4vpunwkfn9zxkpxl8jg0lwuu"
);
```

Expand All @@ -123,20 +122,21 @@ getSpotOrder("your_order_id_here");
getSpotOrder("1");
```

### 5. getSpotOrders(pagination, order_type, owner_address)
### 5. getSpotOrders(pagination, order_type, order_owner, order_status)

This function retrieves information about multiple order by querying a CosmWasm contract on the blockchain.

#### Parameters

- `pagination` {PageRequest} :
- `order_type` (OrderType or null): select the order type that should be querried
- `owner_address` (String or null): select the owner of the order that should be querried
- `order_owner` (String or null): select the owner of the order that should be querried
- `order_status` (String or null) : select the order staus that should be querried (Pending,Executed,Canceled)

#### Usage

```javascript
getSpotOrders({"count_total", "limit", "reverse", "key"}, "order_type", "owner_address")
getSpotOrders({"count_total", "limit", "reverse", "key"}, "order_type", "order_owner", "status")
```

####
Expand All @@ -145,23 +145,25 @@ getSpotOrders({"count_total", "limit", "reverse", "key"}, "order_type", "owner_a
getSpotOrders(
{ count_total: true, limit: 10, reverse: false, key: null },
"stop_loss",
"elys12tzylat4udvjj56uuhu3vj2n4vgp7cf9fwna9w"
"elys12tzylat4udvjj56uuhu3vj2n4vgp7cf9fwna9w",
null
);
```

### 6. createMarginOrder(position, collateral, leverage, borrow_asset, take_profit_price, order_type, trigger_price)
### 6. createMarginOrder(position, collateral, leverage, trading_asset, take_profit_price, order_type, trigger_price)

This function allows you to create a margin order by sending a transaction to the CosmWasm contract.

#### Parameters

- `position` (String): The type of position for the margin order (e.g., "long", "short").
- `collateral` (Coin {demom: String , amount : String}): The amount of collateral for the margin order.
- `leverage` (String): The leverage for the margin order.
- `borrow_asset` (String): The asset to borrow for the margin order.
- `take_profit_price` (String): The price at which the order will take profit.
- `position` (String): The type of position for the margin order (e.g., "long", "short"). Can be null if it's not a LimitOpen or MarketOpen type
- `leverage` (String): The leverage for the margin order.Can be null if it's not a LimitOpen or MarketOpen type
- `trading_asset` (String): The asset to borrow for the margin order. Can be null if it's not a LimitOpen or MarketOpen type
- `take_profit_price` (String): The price at which the order will take profit. Can be null if it's not a LimitOpen or MarketOpen type
- `order_type` (String): The type of the order (e.g., "stop_loss", "limit_sell", "limit_buy").
- `trigger_price` ({`base_denom`:String, `quote_denom`:String, `rate` :String} or null): Price relates two assets exchange rate that the user should define, can only be null if the order type is "market_type"
- `position_id` (u64) Can be null if it's not a LimitClose, MarketClose or StopLoss type

#### Usage

Expand All @@ -170,10 +172,11 @@ createMarginOrder(
"position_type",
"collateral",
"leverage_value",
"borrow_asset",
"trading_asset",
"take_profit_price",
"order_type",
"trigger_price"
"position_id"
);
```

Expand All @@ -188,6 +191,7 @@ createMarginOrder(
"2.2"
"limit_buy",
{ base_denom: "ueth", quote_denom: "uusdc", rate: "2076.5" }
null
);
```

Expand Down Expand Up @@ -217,7 +221,6 @@ This function retrieves information about a specific margin order by querying a

#### Parameters

- `address` (String): The address associated with the margin order.
- `order_id` (String): The unique identifier for the order you want to retrieve.

#### Usage
Expand Down Expand Up @@ -299,6 +302,34 @@ SwapEstimationByDenom({
});
```

### 12. getMarginOrders(pagination, order_type, order_owner, order_status)

This function retrieves information about multiple order by querying a CosmWasm contract on the blockchain.

#### Parameters

- `pagination` {PageRequest} :
- `order_type` (OrderType or null): select the order type that should be querried
- `order_owner` (String or null): select the owner of the order that should be querried
- `order_status` (String or null) : select the order staus that should be querried (pending,executed,canceled)

#### Usage

```javascript
getMarginOrders({"count_total", "limit", "reverse", "key"}, "order_type", "order_owner", status)
```

####

```js
getMarginOrders(
{ count_total: true, limit: 10, reverse: false, key: null },
"stop_loss",
"elys12tzylat4udvjj56uuhu3vj2n4vgp7cf9fwna9w",
"pending"
);
```

## Configuration

Before using these functions, you need to configure the following parameters in the script:
Expand Down
49 changes: 41 additions & 8 deletions front_end_script/upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ async function getSpotOrder(order_id) {
}

async function createSpotOrder(
order_amm_routes,
order_price,
order_type,
amount_send,
Expand All @@ -62,7 +61,6 @@ async function createSpotOrder(
const executeFee = calculateFee(300_000, gasPrice);
const msg = {
create_spot_order: {
order_amm_routes: order_amm_routes,
order_price: order_price,
order_type: order_type,
order_source_denom: denom_send,
Expand Down Expand Up @@ -137,7 +135,40 @@ async function cancelSpotOrders(order_type, owner_address, order_ids) {
console.log("create_spot_orders_res:", create_spot_orders_res);
}

async function getSpotOrders(pagination, order_type, owner_address) {
async function getSpotOrders(
pagination,
order_type,
order_owner,
order_status
) {
const sender_wallet = await DirectSecp256k1HdWallet.fromMnemonic(
sender.mnemonic,
{ prefix: "elys" }
);
const sender_client = await SigningCosmWasmClient.connectWithSigner(
rpcEndpoint,
sender_wallet
);
const result = await sender_client.queryContractSmart(
trade_shield_contract_addr,
{
get_spot_orders: {
pagination: pagination,
order_type: order_type,
order_owner: order_owner,
order_status: order_status,
},
}
);
console.log(`Result: `, result);
}

async function getSpotOrders(
pagination,
order_type,
order_owner,
order_status
) {
const sender_wallet = await DirectSecp256k1HdWallet.fromMnemonic(
sender.mnemonic,
{ prefix: "elys" }
Expand All @@ -152,7 +183,8 @@ async function getSpotOrders(pagination, order_type, owner_address) {
get_spot_orders: {
pagination: pagination,
order_type: order_type,
owner_address: owner_address,
order_owner: order_owner,
order_status: order_status,
},
}
);
Expand Down Expand Up @@ -185,10 +217,11 @@ async function createMarginOrder(
position_type,
collateral,
leverage_value,
borrow_asset,
trading_asset,
take_profit_price,
order_type,
trigger_price
trigger_price,
position_id
) {
const gasPrice = GasPrice.fromString(GASPRICE);
const sender_wallet = await DirectSecp256k1HdWallet.fromMnemonic(
Expand All @@ -203,9 +236,9 @@ async function createMarginOrder(
const msg = {
create_margin_order: {
position_type: position_type,
collateral: collateral,
leverage_value: leverage_value,
borrow_asset: borrow_asset,
trading_asset: trading_asset,
position_id: position_id,
take_profit_price: take_profit_price,
order_type: order_type,
trigger_price: trigger_price,
Expand Down
8 changes: 3 additions & 5 deletions src/action/execute/cancel_margin_order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ pub fn cancel_margin_order(
deps: DepsMut<ElysQuery>,
order_id: u64,
) -> Result<Response<ElysMsg>, ContractError> {
let mut orders = MARGIN_ORDER.load(deps.storage)?;

let order = match orders.iter_mut().find(|order| order.order_id == order_id) {
let mut order = match MARGIN_ORDER.may_load(deps.storage, order_id)? {
Some(order) => order,
None => return Err(ContractError::OrderNotFound { order_id }),
};
Expand All @@ -20,7 +18,7 @@ pub fn cancel_margin_order(
});
}

if order.status != Status::NotProcessed {
if order.status != Status::Pending {
return Err(ContractError::CancelStatusError {
order_id,
status: order.status.clone(),
Expand All @@ -39,7 +37,7 @@ pub fn cancel_margin_order(
.add_attribute("margin_order_id", order.order_id.to_string()),
);

MARGIN_ORDER.save(deps.storage, &orders)?;
MARGIN_ORDER.save(deps.storage, order_id, &order)?;

if order_type == MarginOrderType::LimitOpen {
Ok(resp.add_message(CosmosMsg::Bank(refund_msg)))
Expand Down
Loading

0 comments on commit 16b7711

Please sign in to comment.