8000 refactor: cleaning code and updating deprecated cli by Teolhyn · Pull Request #107 · laina-defi/laina · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

refactor: cleaning code and updating deprecated cli #107

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 21 additions & 16 deletions contracts/loan_manager/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ impl LoanManager {
Ok(())
}

/// Add interest to loan
pub fn add_interest(e: &Env, user: Address) -> Result<(), LoanManagerError> {
const DECIMAL: i128 = 10000000;
let Loan {
Expand Down Expand Up @@ -235,6 +236,7 @@ impl LoanManager {
Ok(())
}

/// Calculate health factor of a given token ratio
pub fn calculate_health_factor(
e: &Env,
token_ticker: Symbol,
Expand Down Expand Up @@ -283,22 +285,7 @@ impl LoanManager {
Ok(health_factor)
}

pub fn get_loan(e: &Env, user: Address) -> Result<Loan, LoanManagerError> {
storage::read_loan(e, user).ok_or(LoanManagerError::LoanNotFound)
}

pub fn get_price(e: &Env, token: Symbol) -> Result<i128, LoanManagerError> {
let reflector_address = Address::from_string(&String::from_str(e, REFLECTOR_ADDRESS));
let reflector_contract = oracle::Client::new(e, &reflector_address);

let asset = Asset::Other(token);

let asset_pricedata = reflector_contract
.lastprice(&asset)
.ok_or(LoanManagerError::NoLastPrice)?;
Ok(asset_pricedata.price)
}

/// Repay part of a loan
pub fn repay(e: &Env, user: Address, amount: i128) -> Result<(i128, i128), LoanManagerError> {
user.require_auth();

Expand Down Expand Up @@ -361,6 +348,7 @@ impl LoanManager {
Ok((borrowed_amount, new_borrowed_amount))
}

/// Repay fully and close a loan
pub fn repay_and_close_manager(
e: &Env,
user: Address,
Expand Down Expand Up @@ -394,6 +382,7 @@ impl LoanManager {
Ok(borrowed_amount)
}

/// Liquidate a given users loan
pub fn liquidate(
e: Env,
user: Address,
Expand Down Expand Up @@ -494,6 +483,22 @@ impl LoanManager {

Ok((new_borrowed_amount, new_collateral_amount))
}

pub fn get_loan(e: &Env, user: Address) -> Result<Loan, LoanManagerError> {
storage::read_loan(e, user).ok_or(LoanManagerError::LoanNotFound)
}

pub fn get_price(e: &Env, token: Symbol) -> Result<i128, LoanManagerError> {
let reflector_address = Address::from_string(&String::from_str(e, REFLECTOR_ADDRESS));
let reflector_contract = oracle::Client::new(e, &reflector_address);

let asset = Asset::Other(token);

let asset_pricedata = reflector_contract
.lastprice(&asset)
.ok_or(LoanManagerError::NoLastPrice)?;
Ok(asset_pricedata.price)
}
}

#[cfg(test)]
Expand Down
8000
102 changes: 51 additions & 51 deletions contracts/loan_pool/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,57 +278,6 @@ impl LoanPoolContract {
Ok(())
}

pub fn get_accrual(e: &Env) -> Result<i128, LoanPoolError> {
storage::read_accrual(e)
}

pub fn get_collateral_factor(e: &Env) -> Result<i128, LoanPoolError> {
storage::read_collateral_factor(e)
}

/// Get user's positions in the storage
pub fn get_user_positions(e: Env, user: Address) -> Positions {
storage::read_positions(&e, &user)
}

/// Get contract data entries
pub fn get_contract_balance(e: Env) -> Result<i128, LoanPoolError> {
storage::read_total_balance(&e)
}

pub fn get_total_balance_shares(e: Env) -> Result<i128, LoanPoolError> {
storage::read_total_shares(&e)
}

pub fn get_available_balance(e: Env) -> Result<i128, LoanPoolError> {
storage::read_available_balance(&e)
}

pub fn get_currency(e: Env) -> Result<Currency, LoanPoolError> {
storage::re 8000 ad_currency(&e)
}

pub fn get_interest(e: Env) -> Result<i128, LoanPoolError> {
interest::get_interest(e)
}

pub fn get_pool_state(e: Env) -> Result<PoolState, LoanPoolError> {
Ok(PoolState {
total_balance_tokens: storage::read_total_balance(&e)?,
available_balance_tokens: storage::read_available_balance(&e)?,
total_balance_shares: storage::read_total_shares(&e)?,
annual_interest_rate: interest::get_interest(e)?,
})
}

pub fn increase_liabilities(e: Env, user: Address, amount: i128) -> Result<(), LoanPoolError> {
let loan_manager_addr = storage::read_loan_manager_addr(&e)?;
loan_manager_addr.require_auth();

positions::increase_positions(&e, user.clone(), 0, amount, 0)?;
Ok(())
}

pub fn repay(
e: Env,
user: Address,
Expand Down Expand Up @@ -445,6 +394,57 @@ impl LoanPoolContract {
positions::decrease_positions(&e, loan_owner, 0, 0, amount_collateral)?;
Ok(())
}

pub fn get_accrual(e: &Env) -> Result<i128, LoanPoolError> {
storage::read_accrual(e)
}

pub fn get_collateral_factor(e: &Env) -> Result<i128, LoanPoolError> {
storage::read_collateral_factor(e)
}

/// Get user's positions in the storage
pub fn get_user_positions(e: Env, user: Address) -> Positions {
storage::read_positions(&e, &user)
}

/// Get contract data entries
pub fn get_contract_balance(e: Env) -> Result<i128, LoanPoolError> {
storage::read_total_balance(&e)
}

pub fn get_total_balance_shares(e: Env) -> Result<i128, LoanPoolError> {
storage::read_total_shares(&e)
}

pub fn get_available_balance(e: Env) -> Result<i128, LoanPoolError> {
storage::read_available_balance(&e)
}

pub fn get_currency(e: Env) -> Result<Currency, LoanPoolError> {
storage::read_currency(&e)
}

pub fn get_interest(e: Env) -> Result<i128, LoanPoolError> {
interest::get_interest(e)
}

pub fn get_pool_state(e: Env) -> Result<PoolState, LoanPoolError> {
Ok(PoolState {
total_balance_tokens: storage::read_total_balance(&e)?,
available_balance_tokens: storage::read_available_balance(&e)?,
total_balance_shares: storage::read_total_shares(&e)?,
annual_interest_rate: interest::get_interest(e)?,
})
}

pub fn increase_liabilities(e: Env, user: Address, amount: i128) -> Result<(), LoanPoolError> {
let loan_manager_addr = storage::read_loan_manager_addr(&e)?;
loan_manager_addr.require_auth();

positions::increase_positions(&e, user.clone(), 0, amount, 0)?;
Ok(())
}
}

#[cfg(test)]
Expand Down
8 changes: 4 additions & 4 deletions currencies.ts
Original file line number Diff line number Diff line change Expand Up @@ -27,18 +27,18 @@ export const CURRENCY_USDC: Currency = { name: 'USD Coin', ticker: 'USDC', issuerName: 'centre.io', tokenContractAddress: 'CAHMBFPE4BNP26VUFRYBJ43GWENCAS2JAGQ7VPBV23CUFL4ZWZQGNBGO', tokenContractAddress: 'CCFOGKTM7CC33YW2H5XSGJN5DLNXG2GUKA3XMRYRWZSY2G5QGW2V3PSO', loanPoolName: 'pool_usdc', issuer: 'GBE3CPBXTOGG75G7GETO5QZBYB4WCDTX6XWUEVZMXFP6Q66OR4MSLIPU', issuer: 'GCAZVAXHZDFF25GIKG3XMUJKMB2IRFUD3N35GUQZMZA5GT66NYHRXBHO', } as const;
export const CURRENCY_EURC: Currency = { name: 'Euro Coin', ticker: 'EURC', issuerName: 'centre.io', tokenContractAddress: 'CDR3UKQ3L5K2JV2OINPVLB6NIOLSROAKMWPEML4CMXBN5NBAUGWFBNYZ', tokenContractAddress: 'CCH2DZNCAG72ARUIMYBAEWM7TXVCB4O32GG3RHULN5GRAP4HE5M4H4XP', loanPoolName: 'pool_eurc', issuer: 'GBE3CPBXTOGG75G7GETO5QZBYB4WCDTX6XWUEVZMXFP6Q66OR4MSLIPU', issuer: 'GCAZVAXHZDFF25GIKG3XMUJKMB2IRFUD3N35GUQZMZA5GT66NYHRXBHO', } as const;
export const CURRENCIES: Currency[] = [CURRENCY_XLM, CURRENCY_USDC, CURRENCY_EURC] as const;
14 changes: 7 additions & 7 deletions scripts/initialize.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'dotenv/config';
import { mkdirSync } from 'fs';
import crypto from 'crypto';
import { CURRENCIES, type Currency } from '../currencies';
import { mkdirSync } from 'node:fs';
import crypto from 'node:crypto';
import { CURRENCIES } from '../currencies';
import {
loadAccount,
buildContracts,
Expand All @@ -28,10 +28,10 @@ const deploy = (wasm: string) => {
* Loan_manager is used as a factory for the loan_pools.
*/
const deployLoanManager = () => {
const contractsDir = `.stellar/contract-ids`;
const contractsDir = '.stellar/contract-ids';
mkdirSync(contractsDir, { recursive: true });

deploy(`./target/wasm32-unknown-unknown/release/loan_manager.wasm`);
deploy('./target/wasm32-unknown-unknown/release/loan_manager.wasm');

exe(`stellar contract invoke \
--id ${loanManagerAddress()} \
Expand All @@ -45,7 +45,7 @@ const deployLoanManager = () => {
const deployLoanPools = () => {
const wasmHash = readTextFile('./.stellar/contract-wasm-hash/loan_pool.txt');

CURRENCIES.forEach(({ tokenContractAddress, ticker, loanPoolName }: Currency) => {
for (const { tokenContractAddress, ticker, loanPoolName } of CURRENCIES) {
const salt = crypto.randomBytes(32).toString('hex');
exe(
`stellar contract invoke \
Expand All @@ -60,7 +60,7 @@ const deployLoanPools = () => {
--liquidation_threshold 8000000 \
| tr -d '"' > ./.stellar/contract-ids/${loanPoolName}.txt`,
);
});
}
};

// Calling the functions (equivalent to the last part of your bash script)
Expand Down
24 changes: 12 additions & 12 deletions scripts/util.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { execSync } from 'child_process';
import { mkdirSync, readFileSync, writeFileSync } from 'fs';
import path from 'path';
import { execSync } from 'node:child_process';
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';

// Load environment variables starting with PUBLIC_ into the environment,
// so we don't need to specify duplicate variables in .env
Expand Down Expand Up @@ -35,24 +35,24 @@ export const exe = (command: string) => {
};

export const buildContracts = () => {
exe(`rm -f ./target/wasm32-unknown-unknown/release/*.wasm`);
exe(`rm -f ./target/wasm32-unknown-unknown/release/*.d`);
exe(`make build`);
exe('rm -f ./target/wasm32-unknown-unknown/release/*.wasm');
exe('rm -f ./target/wasm32-unknown-unknown/release/*.d');
exe('make build');
};

/** Install all contracts and save their wasm hashes to .stellar */
export const installContracts = () => {
const contractsDir = `./.stellar/contract-wasm-hash`;
const contractsDir = './.stellar/contract-wasm-hash';
mkdirSync(contractsDir, { recursive: true });

install('loan_manager');
install('loan_pool');
upload('loan_manager');
upload('loan_pool');
};

/* Install a contract */
const install = (contractName: string) => {
const upload = (contractName: string) => {
exe(
Comment on lines 52 to +53
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should that comment be updated as well?

`stellar contract install \
`stellar contract upload \
--wasm ./target/wasm32-unknown-unknown/release/${contractName}.wasm \
--ignore-checks \
> ./.stellar/contract-wasm-hash/${contractName}.txt`,
Expand Down Expand Up @@ -90,7 +90,7 @@ export const createContractImports = () => {
};

const importContract = (contractName: string) => {
const outputDir = `./src/contracts/`;
const outputDir = './src/contracts/';
mkdirSync(outputDir, { recursive: true });

/* eslint-disable quotes */
Expand Down
Loading
0