Skip to content

Commit

Permalink
Merge pull request #4 from 0xSpaceShard/fix/refacto-and-loop
Browse files Browse the repository at this point in the history
refacto: Add getter in factory for pooling manager and make all contr…
  • Loading branch information
qperrot authored Jan 19, 2024
2 parents 76511eb + 453b7c7 commit 7bca88b
Show file tree
Hide file tree
Showing 24 changed files with 5,112 additions and 748 deletions.
136 changes: 136 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
## Yield Dex

L2 contracts for Yield Dex project.

### Compilation

We are using Scarb to compile our contracts, you need to install it to be able to use it.
For that, you can follow the steps [here](https://book.cairo-lang.org/ch01-01-installation.html).
Once Scarb is installed, you are able to compile the contracts.
Run `scarb build`, it will build Sierra code of this package which will be written to the `target/dev` directory.

### Test

You can find our tests under `src/tests`, these tests are written using snfoundry you can find more information [here](https://foundry-rs.github.io/starknet-foundry/getting-started/installation.html).
Follow the installation documentation to be able to run our tests.
To run the tests, just do `snforge test`.

### Declare With Starkli

For this, we used starkli, you need to install it to be able to declare and deploy the contracts.
Once starkli is installed, you will need to set some environment variables.
If you want to declare on goerli then do `export STARKNET_NETWORK="goerli"` (you replace it be mainnet or sepolia depending on the network you want to deploy to).
You will have to create a signers and account, just follow those [documentation](https://book.starkli.rs/signers).
Now that everything is set up, you are able to declare the contracts.
For that, we will use starkli declare command, for more info check the documentation [here](https://book.starkli.rs/declaring-classes).
Run `starkli declare ./target/dev/CONTRACT_NAME.contract_class.json --account PATH/account-store --network NETWORK`.
`CONTRACT_NAME `the name of the json file that can be found inside `./target/dev/ `folder.
`PATH/account-store` is the path to your account-store that has been previously created.
`NETWORK `the name of the network you want to declare to (goerli, sepolia or mainnet).
After running that, it will return to you the declared contract class hash.

### Declare With Script

Create a `.env` and add `ACCOUNT_ADDRESS` and `ACCOUNT_PK`.
Run `npm i` to install the package.
The script is deploying the contract on goerli if you want to deploy on another network then go inside `scripts/declareContracts` and change `const provider = new RpcProvider({ nodeUrl: constants.NetworkName.SN_MAIN });` with the correct network (ex: SN_GOERLI).
To run the script just do `npx ts-node scripts/declareContracts.ts --contract CONTRACT_NAME.`
`CONTRACT_NAME` must be replaced by :
- PoolingManager
- Factory
- Token
- TokenManager

### Deploy With Starkli

Now that our contracts are declared, the next step is to deploy them. For that, you can follow the documentation [here](https://book.starkli.rs/deploying-contracts).
Some of the contracts take parameters in their constructor, you will need to add them in your command.

PoolingManager: `starkli deploy POOLING_MANAGER_CLASS_HASH OWNER_ACCOUNT_ADDRESS --account PATH/account-store --network NETWORK`
Factory: `starkli deploy FACTORY_CLASS_HASH POOLING_MANAGER_CONTRACT_ADDRESS TOKEN_CLASS_HASH TOKEN_MANAGER_CLASS_HASH --account PATH/account-store --network NETWORK`

### Deploy With Script

Create a `.env` and add `ACCOUNT_ADDRESS` and `ACCOUNT_PK`.
Run `npm i` to install the package.
The script is deploying the contract on goerli if you want to deploy on another network then go inside `scripts/deployContracts` and change `const provider = new RpcProvider({ nodeUrl: constants.NetworkName.SN_MAIN });` with the correct network (ex: `SN_GOERLI`).
To run the script just do `npx ts-node scripts/deployContracts.ts --contract CONTRACT_NAME`.
`CONTRACT_NAME` must be replaced by :
- PoolingManager
- Factory

### Setup
Only the owner of the contract will be able to set up the contract.
You can do the setup through voyager or starkscan.

PoolingManager:
Only Owner:
- set_fees_recipient: Address of the fees recipient.
- set_l1_pooling_manager: Address of the pooling manager on l1.
- set_factory: Address of the Factory contract previously deployed.

Only Role, the owner has the correct role, but you can also give permission to other accounts:
- register_underlying: Registers an underlying asset, its corresponding bridge contract and the corresponding address of the l1bridge

Factory:
Only Owner:
- `deploy_strategy`: Deploys a new strategy with specified parameters.
Parameters are:
- l1_strategy: The Ethereum address of the L1 strategy
- underlying: The contract address of the underlying asset
- token_name: The name for the new token
- token_symbol: The symbol for the new token
- performance_fees: The performance fees for the strategy
- min_deposit: The minimum deposit limit
- max_deposit: The maximum deposit limit
- min_withdrawal: The minimum withdrawal limit
- max_withdrawal: The maximum withdrawal limit
- withdrawal_epoch_delay: The delay in epochs for withdrawals
- dust_limit: The dust limit for the strategy
Deploy_strategy will deploy a new contract called token_manager and return you the address. We are going to use this contract to deposit some tokens.

Go to the Token Manager contract address and call the deposit function, This function can be called by any user :

TokenManager:
- `deposit`: Allows a user to deposit assets into the contract.
Parameters are:
- assets: The amount of assets to deposit.
- receiver: The address to receive the minted shares.
- referral: The referral address for the deposit.
Once users have deposited some assets, they can now request a withdrawal from the contract.
- `request_withdrawal`: Allows a user to request a withdrawal from the contract
Parameter is:
- shares: The amount of shares to withdraw.

### Goerli Class Hash
You can declare a contract only once on each network. So if you don't do any modification into our current contract implementation you may face an error while declaring. Therefore here you can find the current class hash of each contract on Goerli.

```
POOLINGMANAGER_CLASS_HASH="0x05adb7661d0dcb3cc5fbe69380846fb7662c92f1943fcf609c51b756cae7d411"
TOKENMANAGER_CLASS_HASH="0x03be98338455134abae1d830802a162cd81b24ddb38a868ec9c6a4341ecd7210"
TOKENMOCK_CLASS_HASH="0x00da57dbb24ceb46a3901f148442e0d591528baba485ee84ed6d4948dedf12e5"
TOKEN_CLASS_HASH="0x0720f601c0432ab03e12df99c2b215e7ab9a9c12e1b4d8b0473e18bbb3213bea"
TOKENBRIDGE_CLASS_HASH="0x00de6d9bd84775dd221273e833dc44946da586483cf822e0021385de95964700"
FACTORY_CLASS_HASH="0x0581277daf0e409c2537979108b7eb4a5cec3624db552c35f8f6acc9a3ac937b"
```

### Mainnet Class Hash
You can declare a contract only once on each network. So if you don't do any modification into our current contract implementation you may face an error while declaring. Therefore here you can find the current class hash of each contract on Mainnet.

```
POOLINGMANAGER_CLASS_HASH=0x05adb7661d0dcb3cc5fbe69380846fb7662c92f1943fcf609c51b756cae7d411
FACTORY_CLASS_HASH=0x581277daf0e409c2537979108b7eb4a5cec3624db552c35f8f6acc9a3ac937b
TOKENMANAGER_CLASS_HASH=0x3be98338455134abae1d830802a162cd81b24ddb38a868ec9c6a4341ecd7210
TOKEN_CLASS_HASH=0x720f601c0432ab03e12df99c2b215e7ab9a9c12e1b4d8b0473e18bbb3213bea
```

10 changes: 10 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"dependencies": {
"dotenv": "^16.3.1",
"fs": "^0.0.1-security",
"starknet": "^5.24.3"
},
"devDependencies": {
"@types/node": "^20.11.5"
}
}
60 changes: 60 additions & 0 deletions scripts/declareContracts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { Account, Provider, Contract, json, RpcProvider, constants } from 'starknet';
import fs from 'fs';
import dotenv from 'dotenv';

dotenv.config({ path: __dirname + '/../.env' });

const provider = new RpcProvider({ nodeUrl: constants.NetworkName.SN_MAIN });

const owner = new Account(provider, process.env.ACCOUNT_ADDRESS as string, process.env.ACCOUNT_PK as string, "1");

export async function declareContract(name: string) {
const compiledContract = await json.parse(fs.readFileSync(`./target/dev/nimbora_yields_${name}.contract_class.json`).toString('ascii'));
const compiledSierraCasm = await json.parse(fs.readFileSync(`./target/dev/nimbora_yields_${name}.compiled_contract_class.json`).toString('ascii'));
const declareResponse = await owner.declare({
contract: compiledContract,
casm: compiledSierraCasm,
});

console.log('Contract classHash: ', declareResponse.class_hash);
fs.appendFile(__dirname + '/../.env', `\n${name.toUpperCase()}_CLASS_HASH=${declareResponse.class_hash}`, function (err) {
if (err) throw err;
});
}

async function main() {
if (!process.argv[2] || !process.argv[3]) {
throw new Error("Missing --contract <contract_name>");
}

switch (process.argv[3]) {
case "PoolingManager":
console.log("Declaring PoolingManager...");
await declareContract('PoolingManager');

break;

case "Factory":
console.log("Declaring Factory...");
await declareContract('Factory');

break;

case "TokenManager":
console.log("Declaring TokenManager...");
await declareContract('TokenManager');

break;

case "Token":
console.log("Declaring Token...");
await declareContract('Token');

break;

default:
throw new Error("Error: Unknown contract");
}
}

main();
86 changes: 86 additions & 0 deletions scripts/deployContracts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { Account, Provider, Contract, json, uint256, RpcProvider, constants } from "starknet";
import fs from 'fs';
import dotenv from 'dotenv';
import { appendToEnv } from "./utils";

dotenv.config({ path: __dirname + '/../.env' })

const provider = new RpcProvider({ nodeUrl: constants.NetworkName.SN_MAIN });
const owner = new Account(provider, process.env.ACCOUNT_ADDRESS as string, process.env.ACCOUNT_PK as string, "1");

async function deployPoolingManagerContract(): Promise<Contract> {
let contractAddress: any;
const compiledContract = await json.parse(fs.readFileSync(`./target/dev/nimbora_yields_PoolingManager.contract_class.json`).toString('ascii'));

let { transaction_hash, contract_address } = await owner.deploy({
classHash: process.env.POOLINGMANAGER_CLASS_HASH as string,
constructorCalldata: {
owner: owner.address,
},
});
[contractAddress] = contract_address;
// await provider.waitForTransaction(transaction_hash);

const poolingManagerContract = new Contract(compiledContract.abi, contractAddress, owner);
console.log('✅ Test PoolingManager contract connected at =', poolingManagerContract.address);

return poolingManagerContract;
}

async function deployFactoryContract(): Promise<Contract> {
let contractAddress: any;
const compiledContract = await json.parse(fs.readFileSync(`./target/dev/nimbora_yields_Factory.contract_class.json`).toString('ascii'));

let { transaction_hash, contract_address } = await owner.deploy({
classHash: process.env.FACTORY_CLASS_HASH as string,
constructorCalldata: {
pooling_manager: process.env.POOLINGMANAGER_ADDRESS as string,
token_class_hash: process.env.TOKEN_CLASS_HASH as string,
token_manager_class_hash: process.env.TOKENMANAGER_CLASS_HASH as string,
},
});
[contractAddress] = contract_address;
// await provider.waitForTransaction(transaction_hash);

const factoryContract = new Contract(compiledContract.abi, contractAddress, owner);
console.log('✅ Test Factory contract connected at =', factoryContract.address);

return factoryContract;
}




async function main() {

const flag = process.argv[2];
const action = process.argv[3];

if (!flag || !action) {
throw new Error("Missing --contract <contract_name>");
}

if (flag == "--contract") {
switch (action) {
case "PoolingManager":
console.log("Deploying PoolingManager...");

const poolingManagerContract = await deployPoolingManagerContract(
);
break;

case "Factory":
console.log("Deploying Factory...");
const factoryContractAddress = await deployFactoryContract();

break;
}
} else if (flag == "--setup") {
const contract_address = process.argv[4];
if (!contract_address) {
throw new Error("Error: Provide contract address");
}
}
}

main();
12 changes: 12 additions & 0 deletions scripts/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import fs from 'fs';
import dotenv from 'dotenv';

dotenv.config({ path: __dirname + '/../.env' })

export async function appendToEnv(name: string, address: string) {
fs.appendFile(`${__dirname}/../.env`, `\n${name}_ADDRESS=${address}`, function (
err,
) {
if (err) throw err
})
}
23 changes: 23 additions & 0 deletions src/factory/factory.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ mod Factory {
IAccessControlDispatcher, IAccessControlDispatcherTrait
};
use openzeppelin::token::erc20::{ERC20ABIDispatcher, ERC20ABIDispatcherTrait};
use openzeppelin::upgrades::UpgradeableComponent;


// Local imports.
Expand All @@ -25,8 +26,15 @@ mod Factory {
IPoolingManagerDispatcher, IPoolingManagerDispatcherTrait
};

// Components
component!(path: UpgradeableComponent, storage: upgradeable, event: UpgradeableEvent);

impl InternalUpgradeableImpl = UpgradeableComponent::InternalImpl<ContractState>;

#[storage]
struct Storage {
#[substorage(v0)]
upgradeable: UpgradeableComponent::Storage,
pooling_manager: ContractAddress,
token_class_hash: ClassHash,
token_manager_class_hash: ClassHash
Expand All @@ -36,6 +44,8 @@ mod Factory {
#[event]
#[derive(Drop, starknet::Event)]
enum Event {
#[flat]
UpgradeableEvent: UpgradeableComponent::Event,
TokenHashUpdated: TokenHashUpdated,
TokenManagerHashUpdated: TokenManagerHashUpdated
}
Expand Down Expand Up @@ -76,6 +86,13 @@ mod Factory {
self._set_token_manager_class_hash(token_manager_class_hash);
}

/// @notice Upgrade contract
/// @param New contract class hash
#[external(v0)]
fn upgrade(ref self: ContractState, new_class_hash: ClassHash) {
self._assert_only_owner();
self.upgradeable._upgrade(new_class_hash);
}

#[abi(embed_v0)]
impl Factory of IFactory<ContractState> {
Expand All @@ -91,6 +108,12 @@ mod Factory {
self.token_class_hash.read()
}

/// @notice Reads the pooling manager contract address
/// @return The address of the pooling manager
fn pooling_manager_address(self: @ContractState) -> ContractAddress {
self.pooling_manager.read()
}

/// @notice Deploys a new strategy with specified parameters
/// @dev Only callable by the owner of the contract
/// @param l1_strategy The Ethereum address of the L1 strategy
Expand Down
1 change: 1 addition & 0 deletions src/factory/interface.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use starknet::{ContractAddress, ClassHash, eth_address::EthAddress};
trait IFactory<TContractState> {
fn token_manager_class_hash(self: @TContractState) -> ClassHash;
fn token_class_hash(self: @TContractState) -> ClassHash;
fn pooling_manager_address(self: @TContractState) -> ContractAddress;

fn deploy_strategy(
ref self: TContractState,
Expand Down
1 change: 1 addition & 0 deletions src/lib.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ mod pooling_manager;
mod token_manager;
mod factory;
mod token_bridge;
mod mocks;
#[cfg(test)]
mod tests;
3 changes: 3 additions & 0 deletions src/mocks.cairo
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
mod mock_pooling_manager;
mod mock_factory;
mod mock_token_manager;
Loading

0 comments on commit 7bca88b

Please sign in to comment.