Skip to content

Commit

Permalink
feat: add more fuzz tests, add deployment scripts, improve factory
Browse files Browse the repository at this point in the history
  • Loading branch information
kyriediculous committed Apr 12, 2024
1 parent f905e11 commit 139f666
Show file tree
Hide file tree
Showing 8 changed files with 156 additions and 124 deletions.
117 changes: 26 additions & 91 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Foundry Template [![Open in Gitpod][gitpod-badge]][gitpod] [![Github Actions][gha-badge]][gha] [![Foundry][foundry-badge]][foundry] [![License: MIT][license-badge]][license]
# TenderSwap - Unified Liquidity for Staked Assets 🌊 [![Open in Gitpod][gitpod-badge]][gitpod] [![Github Actions][gha-badge]][gha] [![Foundry][foundry-badge]][foundry] [![License: MIT][license-badge]][license]

[gitpod]: https://gitpod.io/#https://github.com/Tenderize/tenderswap
[gitpod-badge]: https://img.shields.io/badge/Gitpod-Open%20in%20Gitpod-FFB45B?logo=gitpod
Expand All @@ -9,81 +9,12 @@
[license]: https://opensource.org/licenses/MIT
[license-badge]: https://img.shields.io/badge/License-MIT-blue.svg

A Foundry-based template for developing Solidity smart contracts, with sensible defaults.
## Overview

## What's Inside
For an overview of the mechanics and implemented mathematics in TenderSwap, check following sources:

- [Forge](https://github.com/foundry-rs/foundry/blob/master/forge): compile, test, fuzz, format, and deploy smart
contracts
- [Forge Std](https://github.com/foundry-rs/forge-std): collection of helpful contracts and cheatcodes for testing
- [PRBTest](https://github.com/PaulRBerg/prb-test): modern collection of testing assertions and logging utilities
- [Prettier](https://github.com/prettier/prettier): code formatter for non-Solidity files
- [Solhint Community](https://github.com/solhint-community/solhint-community): linter for Solidity code

## Getting Started

Click the [`Use this template`](https://github.com/PaulRBerg/foundry-template/generate) button at the top of the page to
create a new repository with this repo as the initial state.

Or, if you prefer to install the template manually:

```sh
$ mkdir my-project
$ cd my-project
$ forge init --template PaulRBerg/foundry-template
$ pnpm install # install Solhint, Prettier, and other Node.js deps
```

If this is your first time with Foundry, check out the
[installation](https://github.com/foundry-rs/foundry#installation) instructions.

## Features

This template builds upon the frameworks and libraries mentioned above, so for details about their specific features,
please consult their respective documentation.

For example, if you're interested in exploring Foundry in more detail, you should look at the
[Foundry Book](https://book.getfoundry.sh/). In particular, you may be interested in reading the
[Writing Tests](https://book.getfoundry.sh/forge/writing-tests.html) tutorial.

### Sensible Defaults

This template comes with a set of sensible default configurations for you to use. These defaults can be found in the
following files:

```text
├── .editorconfig
├── .gitignore
├── .prettierignore
├── .prettierrc.yml
├── .solhint.json
├── foundry.toml
└── remappings.txt
```

### VSCode Integration

This template is IDE agnostic, but for the best user experience, you may want to use it in VSCode alongside Nomic
Foundation's [Solidity extension](https://marketplace.visualstudio.com/items?itemName=NomicFoundation.hardhat-solidity).

For guidance on how to integrate a Foundry project in VSCode, please refer to this
[guide](https://book.getfoundry.sh/config/vscode).

### GitHub Actions

This template comes with GitHub Actions pre-configured. Your contracts will be linted and tested on every push and pull
request made to the `main` branch.

You can edit the CI script in [.github/workflows/ci.yml](./.github/workflows/ci.yml).

## Writing Tests

To write a new test contract, you start by importing [PRBTest](https://github.com/PaulRBerg/prb-test) and inherit from
it in your test contract. PRBTest comes with a pre-instantiated [cheatcodes](https://book.getfoundry.sh/cheatcodes/)
environment accessible via the `vm` property. If you would like to view the logs in the terminal output you can add the
`-vvv` flag and use [console.log](https://book.getfoundry.sh/faq?highlight=console.log#how-do-i-use-consolelog).

This template comes with an example test contract [Foo.t.sol](./test/Foo.t.sol)
- [White Paper](https://whitepaper.tenderize.me/core-architecture/tenderswap)
- [Yellow Paper](https://whitepaper.tenderize.me/tenderswap/yellow-paper)

## Usage

Expand All @@ -94,77 +25,81 @@ This is a list of the most frequently needed commands.
Build the contracts:

```sh
$ forge build
forge build
```

### Clean

Delete the build artifacts and cache directories:

```sh
$ forge clean
forge clean
```

### Compile

Compile the contracts:

```sh
$ forge build
forge build
```

### Coverage

Get a test coverage report:

```sh
$ forge coverage
forge coverage
```

### Deploy

Deploy to Anvil:
Deployments and upgrades can through the `SwapFactory` contract for indexing purposes on the Tenderize Subgraph.

TenderSwap can also be deployed standlone following the same pattern as the `SwapFactory` contract.

### Format

Format the contracts:

```sh
$ forge script script/Deploy.s.sol --broadcast --fork-url http://localhost:8545
forge fmt
```

For this script to work, you need to have a `MNEMONIC` environment variable set to a valid
[BIP39 mnemonic](https://iancoleman.io/bip39/).

For instructions on how to deploy to a testnet or mainnet, check out the
[Solidity Scripting](https://book.getfoundry.sh/tutorials/solidity-scripting.html) tutorial.
or

### Format
```sh
yarn lint:sol
```

Format the contracts:
Format other files:

```sh
$ forge fmt
yarn prettier:write
```

### Gas Usage

Get a gas report:

```sh
$ forge test --gas-report
forge test --gas-report
```

### Lint

Lint the contracts:

```sh
$ pnpm lint
pnpm lint
```

### Test

Run the tests:

```sh
$ forge test
forge test
```

## Notes
Expand Down
2 changes: 1 addition & 1 deletion foundry.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

[profile.default]
bytecode_hash = "none"
fuzz = { runs = 1_000 }
fuzz = { runs = 10_000 }
gas_reports = ["*"]
libs = ["lib"]
# optimizer = true (default)
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"scripts": {
"clean": "rm -rf cache out",
"lint": "yarn lint:sol && yarn prettier:write",
"lint:sol": "yarn solhint {src,test}/**/*.sol",
"lint:sol": "forge fmt && yarn solhint src/**/*.sol",
"prettier:check": "prettier --check **/*.{json,md,yml} --ignore-path=.prettierignore",
"prettier:write": "prettier --write **/*.{json,md,yml} --ignore-path=.prettierignore"
}
Expand Down
27 changes: 27 additions & 0 deletions script/Factory_Deploy.s.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import { Script, console2 } from "forge-std/Script.sol";
import { SwapFactory } from "@tenderize/swap/Factory.sol";
import { ERC1967Proxy } from "openzeppelin-contracts/proxy/ERC1967/ERC1967Proxy.sol";

address constant FACTORY = address(0);

contract Swap_Deploy is Script {
// Contracts are deployed deterministically.
// e.g. `foo = new Foo{salt: salt}(constructorArgs)`
// The presence of the salt argument tells forge to use https://github.com/Arachnid/deterministic-deployment-proxy
bytes32 private constant salt = 0x0;

// Start broadcasting with private key from `.env` file
uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY");

function run() public {
vm.startBroadcast(deployerPrivateKey);
address fac = address(new SwapFactory());
address proxy = address(new ERC1967Proxy(fac, abi.encodeWithSelector(SwapFactory.initialize.selector)));
console2.log("SwapFactory deployed at: ", proxy);
console2.log("Implementation deployed at: ", fac);
vm.stopBroadcast();
}
}
15 changes: 9 additions & 6 deletions script/Swap_Deploy.s.sol
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { ERC20 } from "solmate/tokens/ERC20.sol";
import { TenderSwap, ConstructorConfig } from "@tenderize/swap/Swap.sol";
import { SwapFactory } from "@tenderize/swap/Factory.sol";
import { SD59x18 } from "@prb/math/SD59x18.sol";
import { ERC1967Proxy } from "openzeppelin-contracts/proxy/ERC1967/ERC1967Proxy.sol";

address constant FACTORY = address(0);

Expand All @@ -18,15 +19,17 @@ contract Swap_Deploy is Script {
// Start broadcasting with private key from `.env` file
uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY");
address underlying = vm.envAddress("UNDERLYING");
address registry = vm.envAddress("REGISTRY");
address unlocks = vm.envAddress("UNLOCKS");
ConstructorConfig cfg =
ConstructorConfig({ UNDERLYING: ERC20(underlying), BASE_FEE: SD59x18.wrap(0.0005e18), K: SD59x18.wrap(3e18) });
SD59x18 BASE_FEE = SD59x18.wrap(vm.envInt("BASE_FEE"));
SD59x18 K = SD59x18.wrap(vm.envInt("K"));

ConstructorConfig cfg = ConstructorConfig({ UNDERLYING: ERC20(underlying), BASE_FEE: BASE_FEE, K: K });

function run() public {
vm.startBroadcast(deployerPrivateKey);
TenderSwap swap = new TenderSwap{ salt: salt }(cfg);
console2.log("TenderSwap deployed at: ", address(swap));
(address proxy, address implementation) = SwapFactory(FACTORY).deploy(cfg);
console2.log("Deployment for ", underlying);
console2.log("TenderSwap deployed at: ", proxy);
console2.log("Implementation deployed at: ", implementation);
vm.stopBroadcast();
}
}
33 changes: 24 additions & 9 deletions src/Factory.sol
Original file line number Diff line number Diff line change
Expand Up @@ -15,32 +15,47 @@ import { Owned } from "solmate/auth/Owned.sol";
import { ERC1967Proxy } from "openzeppelin-contracts/proxy/ERC1967/ERC1967Proxy.sol";
import { TenderSwap, ConstructorConfig } from "@tenderize/swap/Swap.sol";

import { OwnableUpgradeable } from "openzeppelin-contracts-upgradeable/access/OwnableUpgradeable.sol";
import { Initializable } from "openzeppelin-contracts-upgradeable/proxy/utils/Initializable.sol";
import { UUPSUpgradeable } from "openzeppelin-contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";

// Used for subgraph indexing and atomic deployments

contract SwapFactory is Owned {
contract SwapFactory is Initializable, UUPSUpgradeable, OwnableUpgradeable {
event SwapDeployed(address underlying, address swap, address implementation);
event SwapUpgraded(address underlying, address swap, address implementation);

constructor(address _owner) Owned(_owner) { }
function initialize() public initializer {
__Ownable_init();
__UUPSUpgradeable_init();
}

function deploy(ConstructorConfig memory cfg) external onlyOwner {
constructor() {
_disableInitializers();
}

function deploy(ConstructorConfig memory cfg) external onlyOwner returns (address proxy, address implementation) {
// Deploy the implementation
address implementation = address(new TenderSwap(cfg));
implementation = address(new TenderSwap(cfg));
// deploy the contract
address instance = address(new ERC1967Proxy(implementation, ""));
proxy = address(new ERC1967Proxy(implementation, abi.encodeWithSelector(TenderSwap.initialize.selector)));

TenderSwap(instance).transferOwnership(owner);
TenderSwap(proxy).transferOwnership(owner());

emit SwapDeployed(address(cfg.UNDERLYING), instance, implementation);
emit SwapDeployed(address(cfg.UNDERLYING), proxy, implementation);
}

function upgrade(ConstructorConfig memory cfg, address swapProxy) external onlyOwner {
function upgrade(ConstructorConfig memory cfg, address swapProxy) external onlyOwner returns (address implementation) {
if (TenderSwap(swapProxy).UNDERLYING() != cfg.UNDERLYING) {
revert("SwapFactory: UNDERLYING_MISMATCH");
}

address implementation = address(new TenderSwap(cfg));
implementation = address(new TenderSwap(cfg));

TenderSwap(swapProxy).upgradeTo(implementation);
}

///@dev required by the OZ UUPS module
// solhint-disable-next-line no-empty-blocks
function _authorizeUpgrade(address) internal override onlyOwner { }
}
10 changes: 5 additions & 5 deletions src/Swap.sol
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ import { UnlockQueue } from "@tenderize/swap/UnlockQueue.sol";

pragma solidity 0.8.20;

Registry constant REGISTRY = Registry(0xa7cA8732Be369CaEaE8C230537Fc8EF82a3387EE);
ERC721 constant UNLOCKS = ERC721(0xb98c7e67f63d198BD96574073AD5B3427a835796);
address constant TREASURY = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419;

error ErrorNotMature(uint256 maturity, uint256 timestamp);
error ErrorAlreadyMature(uint256 maturity, uint256 timestamp);
error ErrorInvalidAsset(address asset);
Expand Down Expand Up @@ -112,11 +116,7 @@ contract TenderSwap is Initializable, UUPSUpgradeable, OwnableUpgradeable, SwapS
// Cut of the fee for the relayer when an unlock is redeemed
UD60x18 public constant RELAYER_CUT = UD60x18.wrap(0.01e18);

Registry private constant REGISTRY = Registry(0xa7cA8732Be369CaEaE8C230537Fc8EF82a3387EE);
ERC721 private constant UNLOCKS = ERC721(0xb98c7e67f63d198BD96574073AD5B3427a835796);
address private constant TREASURY = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419;

function intialize() public initializer {
function initialize() public initializer {
Data storage $ = _loadStorageSlot();
$.lpToken = new LPToken(UNDERLYING.name(), UNDERLYING.symbol());
__Ownable_init();
Expand Down
Loading

0 comments on commit 139f666

Please sign in to comment.