Skip to content

Commit

Permalink
Merge pull request #21 from securesecrets/dev
Browse files Browse the repository at this point in the history
Add Minting and Oracle contract
  • Loading branch information
FloppyDisck authored Aug 4, 2021
2 parents 9b7357c + 6a6dccd commit 1f30218
Show file tree
Hide file tree
Showing 285 changed files with 2,910 additions and 33,658 deletions.
297 changes: 121 additions & 176 deletions Cargo.lock

Large diffs are not rendered by default.

14 changes: 1 addition & 13 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,14 +1,2 @@
[workspace]
members = ["packages/*", "shade-contracts/*"]

[profile.release.package.mirror-protocol]
opt-level = 3
debug = false
debug-assertions = false
codegen-units = 1
incremental = false

[profile.release]
rpath = false
lto = true
overflow-checks = true
members = ["contracts/mint","contracts/oracle", "packages/shade_protocol"]
205 changes: 159 additions & 46 deletions LICENSE

Large diffs are not rendered by default.

79 changes: 26 additions & 53 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,45 +1,33 @@
# Shade Protocol Core Contracts
| Contract | Reference | Description |
| --------------------------------------------------- | ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- |
| [Placeholder]() | [Placeholder]() | [Placeholder] |
| [Placeholder]() | [Placeholder]() | [Placeholder] |
| [Placeholder]() | [Placeholder]() | [Placeholder] |
| [Placeholder]() | [Placeholder]() | [Placeholder] |
| [Placeholder]() | [Placeholder]() | [Placeholder] |
|[Placeholder]() | [Placeholder]() | [Placeholder] |
| [Placeholder]() | [Placeholder]() |[Placeholder] |
| Contract | Reference | Description |
| --------------------------- | --------------------------------- | ------------------------------------- |
| [`mint`](./contracts/mint) | [doc](./contracts/mint/README.md) | Handles asset burning and silk minting|

## Development

## Development Environment
Instlal docker for local envirnment

# Mirror Core Contracts

This monorepository contains the source code for the core smart contracts implementing Mirror Protocol on the [Terra](https://terra.money) blockchain.

You can find information about the architecture, usage, and function of the smart contracts on the official Mirror documentation [site](https://docs.mirror.finance/contracts/architecture).

### Dependencies

Mirror depends on [Terraswap](https://terraswap.io) and uses its [implementation](https://github.com/terraswap/terraswap) of the CW20 token specification.
Source from [testner](https://build.scrt.network/dev/quickstart.html#setup-the-local-developer-testnet)

## Contracts
```
docker run -it --rm -p 26657:26657 -p 26656:26656 -p 1337:1337 -v $(pwd):/root/code --name secretdev enigmampc/secret-network-sw-dev
| Contract | Reference | Description |
| --------------------------------------------------- | ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- |
| [`mirror_collector`](./contracts/mirror_collector) | [doc](https://docs.mirror.finance/contracts/collector) | Gathers protocol fees incurred from CDP withdrawals and liquidations and sends to Gov |
| [`mirror_community`](../contracts/mirror_community) | [doc](https://docs.mirror.finance/contracts/community) | Manages the commuinty pool fund |
| [`mirror_factory`](./contracts/mirror_factory) | [doc](https://docs.mirror.finance/contracts/factory) | Central directory that organizes the various component contracts of Mirror |
| [`mirror_gov`](./contracts/mirror_gov) | [doc](https://docs.mirror.finance/contracts/gov) | Allows other Mirror contracts to be controlled by decentralized governance, distributes MIR received from Collector to MIR stakers |
| [`mirror_mint`](./contracts/mirror_mint) | [doc](https://docs.mirror.finance/contracts/mint) | Handles CDP creation, management and liquidation |
| [`mirror_oracle`](./contracts/mirror_oracle) | [doc](https://docs.mirror.finance/contracts/oracle) | Provides interface for oracle feeders to post prices for mAssets |
| [`mirror_staking`](./contracts/mirror_staking) | [doc](https://docs.mirror.finance/contracts/staking) | Distributes MIR rewards from block reward to LP stakers |
docker exec -it secretdev /bin/bash
## Development
```
#### Testing the environment
Inside the container:
```
run python3 contract_tester.py
```

### Environment Setup

- Rust v1.44.1+
- `wasm32-unknown-unknown` target
- Docker
- binaryen

1. Install `rustup` via https://rustup.rs/

Expand All @@ -52,6 +40,11 @@ rustup target add wasm32-unknown-unknown

3. Make sure [Docker](https://www.docker.com/) is installed

4. To compile the contracts install binaryen
```sh
apt install binaryen
```

### Unit / Integration Tests

Each contract contains Rust unit and integration tests embedded within the contract source directories. You can run:
Expand All @@ -63,32 +56,12 @@ cargo integration-test

### Compiling

After making sure tests pass, you can compile each contract with the following:

```sh
RUSTFLAGS='-C link-arg=-s' cargo wasm
cp ../../target/wasm32-unknown-unknown/release/cw1_subkeys.wasm .
ls -l cw1_subkeys.wasm
sha256sum cw1_subkeys.wasm
```

#### Production

For production builds, run the following:
Run this script to run all of the contract's unit / integration tests and then prepare the contracts for production in /contracts/compiled:

```sh
docker run --rm -v "$(pwd)":/code \
--mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \
--mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \
cosmwasm/workspace-optimizer:0.10.2
bash ./compile-contracts.sh
```

This performs several optimizations which can significantly reduce the final size of the contract binaries, which will be available inside the `artifacts/` directory.

## License

Copyright 2020 Mirror Protocol

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
### Testing

See the License for the specific language governing permissions and limitations under the License.
You can optionally run extended tests inside a private testnet using the [contract tester](./contracts/compiled/contract_tester.py)
10 changes: 0 additions & 10 deletions artifacts/checksums.txt

This file was deleted.

Binary file removed artifacts/mirror_collateral_oracle.wasm
Binary file not shown.
Binary file removed artifacts/mirror_collector.wasm
Binary file not shown.
Binary file removed artifacts/mirror_community.wasm
Binary file not shown.
Binary file removed artifacts/mirror_factory.wasm
Binary file not shown.
Binary file removed artifacts/mirror_gov.wasm
Binary file not shown.
Binary file removed artifacts/mirror_limit_order.wasm
Binary file not shown.
Binary file removed artifacts/mirror_lock.wasm
Binary file not shown.
Binary file removed artifacts/mirror_mint.wasm
Binary file not shown.
Binary file removed artifacts/mirror_oracle.wasm
Binary file not shown.
Binary file removed artifacts/mirror_staking.wasm
Binary file not shown.
19 changes: 19 additions & 0 deletions compile-contracts.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#!/bin/bash

root_dir=$(git rev-parse --show-toplevel)
contracts_dir="${root_dir}/contracts"
compiled_dir="${contracts_dir}/compiled"

compile_contract() {
# Run tests
(cd ${contracts_dir}/$1; cargo unit-test)
(cd ${contracts_dir}/$1; cargo integration-test)
(cd ${compiled_dir}; rm $1.wasm.gz)
(cd ${contracts_dir}; cargo build --release --target wasm32-unknown-unknown --locked)
wasm-opt -Oz ./target/wasm32-unknown-unknown/release/$1.wasm -o ./$1.wasm
cat ./$1.wasm | gzip -n -9 > ${compiled_dir}/$1.wasm.gz
rm -f ./$1.wasm
}

compile_contract "mint"
compile_contract "oracle"
Empty file added contracts/compiled/__init__.py
Empty file.
63 changes: 63 additions & 0 deletions contracts/compiled/contract_tester.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import random
from contractlib.secretlib import secretlib
from contractlib.snip20lib import SNIP20
from contractlib.mintlib import Mint
from contractlib.oraclelib import Oracle
from contractlib.utils import gen_label

account_key = 'a'
account = secretlib.run_command(['secretcli', 'keys', 'show', '-a', account_key]).rstrip()

print("Configuring sSCRT")
sscrt = SNIP20(gen_label(8), decimals=6, public_total_supply=True, enable_deposit=True)
sscrt_password = sscrt.set_view_key(account_key, "password")
sscrt.print()

sscrt_mint_amount = '100000000000000'
print(f"\tDepositing {sscrt_mint_amount} uSCRT")
sscrt.deposit(account, sscrt_mint_amount + "uscrt")
sscrt_minted = sscrt.get_balance(account, sscrt_password)
print(f"\tReceived {sscrt_minted} usSCRT")
assert sscrt_mint_amount == sscrt_minted, f"Minted {sscrt_minted}; expected {sscrt_mint_amount}"

print("Configuring silk")
silk = SNIP20(gen_label(8), decimals=6, public_total_supply=True, enable_mint=True)
silk_password = silk.set_view_key(account_key, "password")

print('Configuring Oracle')
oracle = Oracle(gen_label(8))
price = int(oracle.get_silk_price()["price"])
print(price / (10**18))

print("Configuring Mint contract")
mint = Mint(gen_label(8), silk, oracle)
silk.set_minters([mint.address])
mint.register_asset(sscrt)
assets = mint.get_supported_assets()['supported_assets']['assets'][0]
assert sscrt.address == assets, f"Got {assets}; expected {sscrt.address}"

print("Sending to mint contract")

total_amount = int(sscrt_mint_amount)
minimum_amount = 1000
total_tests = 5

total_sent = 0

for i in range(total_tests):
send_amount = random.randint(minimum_amount, int(total_amount/total_tests)-1)
total_sent += send_amount

print(f"\tSending {send_amount} usSCRT")
sscrt.send(account_key, mint.address, send_amount)
silk_minted = silk.get_balance(account, silk_password)
#assert total_sent == int(silk_minted), f"Total minted {silk_minted}; expected {total_sent}"

print(f"\tSilk balance: {silk_minted} uSILK")
burned_amount = mint.get_asset(sscrt)["asset"]["asset"]["burned_tokens"]
print(f"\tTotal burned: {burned_amount} usSCRT\n")
#assert total_sent == int(burned_amount), f"Burnt {burned_amount}; expected {total_sent}"

print("Testing migration")
new_mint = mint.migrate(gen_label(8), int(mint.contract_id), mint.code_hash)
assert mint.get_supported_assets() == new_mint.get_supported_assets(), "Contracts are not the same"
Empty file.
63 changes: 63 additions & 0 deletions contracts/compiled/contractlib/contractlib.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
from .secretlib import secretlib


class PreInstantiatedContract:
def __init__(self, contract_id, address, code_hash):
self.contract_id = contract_id
self.address = address
self.code_hash = code_hash


class Contract:
def __init__(self, contract, initMsg, label, admin='a', uploader='a', gas='10000000', backend='test', wait=6,
instantiated_contract=None):
self.label = label
self.admin = admin
self.uploader = uploader
self.gas = gas
self.backend = backend
self.wait = wait

if instantiated_contract is None:
self.contract_id = secretlib.store_contract(contract, uploader, gas, backend)
initResponse = secretlib.instantiate_contract(str(self.contract_id), initMsg, label, admin, backend)
contracts = secretlib.list_code()
self.code_hash = contracts[int(self.contract_id) - 1]["data_hash"]
for attribute in initResponse["logs"][0]["events"][0]["attributes"]:
if attribute["key"] == "contract_address":
self.address = attribute["value"]
break

else:
self.contract_id = instantiated_contract.contract_id
self.code_hash = instantiated_contract.code_hash
self.address = instantiated_contract.address

def execute(self, msg, sender=None, amount=None, compute=True):
"""
Execute said msg
:param msg: Execute msg
:param sender: Who will be sending the message, defaults to contract admin
:param amount: Optional string amount to send along with transaction
:return: Result
"""
signer = sender if sender is not None else self.admin
return secretlib.execute_contract(self.address, msg, signer, self.backend, amount, compute)

def query(self, msg):
"""
Query said msg
:param msg: Query msg
:return: Query
"""
return secretlib.query_contract(self.address, msg)

def print(self):
"""
Prints the contract info
:return:
"""
print(f"Label: {self.label}\n"
f"Address: {self.address}\n"
f"Id: {self.contract_id}\n"
f"Hash: {self.code_hash}")
Loading

0 comments on commit 1f30218

Please sign in to comment.