Skip to content

Commit

Permalink
Merge pull request #10 from DeFiCh/vaults
Browse files Browse the repository at this point in the history
Vaults
  • Loading branch information
Jouzo authored Jul 15, 2024
2 parents 550743d + d216e6a commit 9a338f8
Show file tree
Hide file tree
Showing 3 changed files with 222 additions and 54 deletions.
130 changes: 116 additions & 14 deletions client/src/traits/vault.rs
Original file line number Diff line number Diff line change
@@ -1,39 +1,141 @@
use crate::{Result, RpcApi};
use async_trait::async_trait;
use defichain_rpc_json::{common::UTXO, vault::*};

use crate::{into_json, obj_into_json, Client, Result, RpcApi};

#[async_trait]
pub trait VaultRPC: RpcApi {
fn close_vault(&self, close_vault: CloseVault, utxos: Option<UTXO>) -> Result<String>;
fn create_vault(&self, vault: CreateVault, utxos: Option<UTXO>) -> Result<String>;
fn deposit_to_vault(&self, deposit_vault: DepositVault, utxos: Option<UTXO>) -> Result<String>;
fn estimate_collateral(&self, target_ratio: u64) -> Result<()>;
fn estimate_loan(
async fn close_vault(&self, close_vault: CloseVault, utxos: Option<UTXO>) -> Result<String>;
async fn create_vault(&self, vault: CreateVault, utxos: Option<UTXO>) -> Result<String>;
async fn deposit_to_vault(
&self,
deposit_vault: DepositVault,
utxos: Option<UTXO>,
) -> Result<String>;
async fn estimate_collateral(
&self,
target_ratio: u64,
token_split: TokenPercentageSplit,
) -> Result<()>;
async fn estimate_loan(
&self,
vault_id: String,
token_split: TokenPercentageSplit,
target_ratio: Option<u64>,
) -> Result<()>;
fn estimate_vault(&self) -> Result<VaultEstimation>;
fn get_vault(&self, vault_id: String) -> Result<()>;
fn list_auction_history(
async fn estimate_vault(&self) -> Result<VaultEstimation>;
async fn get_vault(&self, vault_id: String, verbose: Option<bool>) -> Result<VaultResult>;
async fn list_auction_history(
&self,
owner: Option<String>,
pagination: Option<ListAuctionHistoryPagination>,
) -> Result<Vec<ListAuctionHistoryDetail>>;
fn list_auctions(&self) -> Result<Vec<VaultLiquidation>>;
fn list_vaults(&self) -> Result<VaultActive>;
fn place_auction_bid(
async fn list_auctions(&self, pagination: Option<AuctionPagination>) -> Result<Vec<VaultLiquidation>>;
async fn list_vaults(
&self,
options: ListVaultOptions,
pagination: VaultPagination,
) -> Result<Vec<VaultResult>>;
async fn place_auction_bid(
&self,
place_auction_bid: PlaceAuctionBid,
utxos: Option<UTXO>,
) -> Result<String>;
fn update_vault(
async fn update_vault(
&self,
vault_id: String,
vault: UpdateVault,
utxos: Option<UTXO>,
) -> Result<String>;
fn withdraw_from_vault(
async fn withdraw_from_vault(
&self,
withdraw_vault: WithdrawVault,
utxos: Option<UTXO>,
) -> Result<String>;
}

#[async_trait]
impl VaultRPC for Client {
async fn close_vault(&self, close_vault: CloseVault, utxos: Option<UTXO>) -> Result<String> {
self.call("closevault", &[into_json(close_vault)?, into_json(utxos)?]).await
}
async fn create_vault(&self, vault: CreateVault, utxos: Option<UTXO>) -> Result<String> {
self.call("createvault", &[into_json(vault)?, into_json(utxos)?]).await
}
async fn deposit_to_vault(
&self,
deposit_vault: DepositVault,
utxos: Option<UTXO>,
) -> Result<String> {
self.call("deposittovault", &[into_json(deposit_vault)?, into_json(utxos)?]).await
}
async fn estimate_collateral(
&self,
target_ratio: u64,
token_split: TokenPercentageSplit,
) -> Result<()> {
self.call("estimatecollateral", &[into_json(target_ratio)?, into_json(token_split)?]).await
}
async fn estimate_loan(
&self,
vault_id: String,
token_split: TokenPercentageSplit,
target_ratio: Option<u64>,
) -> Result<()> {
self.call(
"estimateloan",
&[into_json(vault_id)?, into_json(token_split)?, into_json(target_ratio)?],
)
.await
}
async fn estimate_vault(&self) -> Result<VaultEstimation> {
self.call("estimatevault", &[]).await
}
async fn get_vault(&self, vault_id: String, verbose: Option<bool>) -> Result<VaultResult> {
self.call("getvault", &[into_json(vault_id)?, into_json(verbose.unwrap_or_default())?])
.await
}
async fn list_auction_history(
&self,
owner: Option<String>,
pagination: Option<ListAuctionHistoryPagination>,
) -> Result<Vec<ListAuctionHistoryDetail>> {
self.call("listauctionhistory", &[into_json(owner)?, into_json(pagination)?]).await
}
async fn list_auctions(
&self,
pagination: Option<AuctionPagination>
) -> Result<Vec<VaultLiquidation>> {
self.call("listauctions", &[obj_into_json(pagination)?]).await
}
async fn list_vaults(
&self,
options: ListVaultOptions,
pagination: VaultPagination,
) -> Result<Vec<VaultResult>> {
self.call("listvaults", &[into_json(options)?, into_json(pagination)?]).await
}
async fn place_auction_bid(
&self,
place_auction_bid: PlaceAuctionBid,
utxos: Option<UTXO>,
) -> Result<String> {
self.call("placeauctionbid", &[into_json(place_auction_bid)?, into_json(utxos)?]).await
}
async fn update_vault(
&self,
vault_id: String,
vault: UpdateVault,
utxos: Option<UTXO>,
) -> Result<String> {
self.call("updatevault", &[into_json(vault_id)?, into_json(vault)?, into_json(utxos)?])
.await
}
async fn withdraw_from_vault(
&self,
withdraw_vault: WithdrawVault,
utxos: Option<UTXO>,
) -> Result<String> {
self.call("withdrawfromvault", &[into_json(withdraw_vault)?, into_json(utxos)?]).await
}
}
3 changes: 1 addition & 2 deletions json/src/loan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,11 @@ pub struct DestroyLoanScheme {
activate_after_block: Option<u64>,
}

#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct LoanSchemeResult {
pub id: String,
pub mincolratio: i64,
pub interestrate: f64,
default: bool,
}

#[derive(Debug, Serialize, Deserialize)]
Expand Down
143 changes: 105 additions & 38 deletions json/src/vault.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
use std::collections::HashMap;
use std::{fmt, collections::HashMap};
use serde::{
de::{Error, Visitor},
Deserialize, Deserializer, Serialize, Serializer,
};

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
Expand All @@ -14,15 +18,58 @@ pub struct UpdateVault {
loan_scheme_id: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
#[derive(Debug)]
pub enum VaultState {
Unknown,
Active,
InLiquidation,
Frozen,
MayLiquidate,
}

impl Serialize for VaultState {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match *self {
VaultState::Unknown => serializer.serialize_str("unknown"),
VaultState::Active => serializer.serialize_str("active"),
VaultState::InLiquidation => serializer.serialize_str("inLiquidation"),
VaultState::Frozen => serializer.serialize_str("frozen"),
VaultState::MayLiquidate => serializer.serialize_str("mayLiquidate"),
}
}
}

impl<'a> Deserialize<'a> for VaultState {
fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<VaultState, D::Error> {
struct VaultStateVisitor;

impl<'de> Visitor<'de> for VaultStateVisitor {
type Value = VaultState;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("`Unknown`, `Active`, `InLiquidation`, `Frozon`, `MayLiquidate`")
}

fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E>
{
match v {
"active" => Ok(VaultState::Active),
"inLiquidation" => Ok(VaultState::InLiquidation),
"frozen" => Ok(VaultState::Frozen),
"mayLiquidation" => Ok(VaultState::MayLiquidate),
_ => Ok(VaultState::Unknown),
}
}
}

deserializer.deserialize_identifier(VaultStateVisitor)
}
}

impl VaultState {
fn in_liquidation() -> Self { VaultState::InLiquidation }
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Vault {
Expand All @@ -35,26 +82,38 @@ pub struct Vault {
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VaultActive {
collateral_amounts: Vec<String>,
loan_amounts: Vec<String>,
interest_amounts: Vec<String>,
collateral_value: i64,
loan_value: i64,
interest_value: i64,
collateral_ratio: u64,
informative_ratio: i64,
next_collateral_ratio: Option<i64>,
interest_per_block_value: Option<String>,
interests_per_block: Option<Vec<String>>,
pub vault_id: String,
pub loan_scheme_id: String,
pub owner_address: String,
pub state: VaultState,
pub collateral_amounts: Vec<String>,
pub loan_amounts: Vec<String>,
pub interest_amounts: Vec<String>,
pub collateral_value: f64,
pub loan_value: f64,
pub interest_value: f64,
pub collateral_ratio: i64,
pub informative_ratio: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub next_collateral_ratio: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub interest_per_block_value: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub interests_per_block: Option<Vec<String>>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VaultLiquidation {
liquidation_height: u64,
liquidation_penalty: u64,
batch_count: u64,
batches: Vec<VaultLiquidationBatch>,
pub vault_id: String,
pub loan_scheme_id: String,
pub owner_address: String,
#[serde(default = "VaultState::in_liquidation")]
pub state: VaultState,
pub liquidation_height: u64,
pub liquidation_penalty: f64,
pub batch_count: usize,
pub batches: Vec<VaultLiquidationBatch>,
}

#[derive(Debug, Serialize, Deserialize)]
Expand All @@ -73,21 +132,21 @@ pub struct WithdrawVault {
amount: String,
}

#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct VaultPagination {
start: Option<String>,
including_start: Option<bool>,
limit: Option<u64>,
pub start: Option<String>,
pub including_start: Option<bool>,
pub limit: Option<usize>,
}

#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ListVaultOptions {
owner_address: Option<String>,
loan_scheme_id: Option<String>,
state: Option<VaultState>,
verbose: Option<bool>,
pub owner_address: Option<String>,
pub loan_scheme_id: Option<String>,
pub state: Option<VaultState>,
pub verbose: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize)]
Expand All @@ -109,32 +168,32 @@ pub struct PlaceAuctionBid {
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuctionPagination {
start: Option<AuctionPaginationStart>,
including_start: Option<bool>,
limit: Option<u64>,
pub start: Option<AuctionPaginationStart>,
pub including_start: Option<bool>,
pub limit: Option<usize>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuctionPaginationStart {
vault_id: Option<String>,
height: Option<u64>,
pub vault_id: String,
pub height: u64,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VaultLiquidationBatch {
index: u64,
collaterals: Vec<String>,
loan: String,
highest_bid: Option<HighestBid>,
pub index: u32,
pub collaterals: Vec<String>,
pub loan: String,
pub highest_bid: Option<HighestBid>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HighestBid {
amount: String,
owner: String,
pub amount: String,
pub owner: String,
}

#[derive(Debug, Serialize, Deserialize)]
Expand Down Expand Up @@ -170,3 +229,11 @@ pub struct VaultEstimation {

#[derive(Debug, Serialize, Deserialize)]
pub struct TokenPercentageSplit(HashMap<String, u64>);

#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum VaultResult {
VaultActive(VaultActive), // Verbose active
VaultLiquidation(VaultLiquidation), // Verbose in liquidation
// Vault(Vault), // Any state non-verbose
}

0 comments on commit 9a338f8

Please sign in to comment.