1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
use std::sync::Arc;

use raiden_primitives::types::{
	Address,
	BlockHash,
	BlockId,
	BlockNumber,
	TokenAmount,
	H256,
	U256,
};
use tokio::sync::RwLock;
use web3::{
	contract::{
		Contract,
		Options,
	},
	Transport,
	Web3,
};

use super::{
	common::Account,
	ProxyError,
	TokenProxy,
};
use crate::{
	contracts::GasMetadata,
	transactions::{
		DepositTransaction,
		DepositTransactionParams,
		PlanWithdrawTransaction,
		PlanWithdrawTransactionParams,
		Transaction,
		WithdrawTransaction,
		WithdrawTransactionParams,
	},
};

/// User deposit error type.
type Result<T> = std::result::Result<T, ProxyError>;

/// Information about planned withdraw.
#[derive(Clone)]
pub struct WithdrawPlan {
	pub withdraw_amount: TokenAmount,
	pub withdraw_block: BlockNumber,
}

/// User deposit proxy to interact with the on-chain contract.
#[derive(Clone)]
pub struct UserDeposit<T: Transport> {
	web3: Web3<T>,
	gas_metadata: Arc<GasMetadata>,
	pub(crate) contract: Contract<T>,
	lock: Arc<RwLock<bool>>,
}

impl<T> UserDeposit<T>
where
	T: Transport + Send + Sync,
	T::Out: Send,
{
	/// Returns a new instance of `UserDeposit`.
	pub fn new(web3: Web3<T>, gas_metadata: Arc<GasMetadata>, contract: Contract<T>) -> Self {
		Self { web3, gas_metadata, contract, lock: Arc::new(RwLock::new(true)) }
	}

	/// Get the user deposit token contract address.
	pub async fn token_address(&self, block: Option<BlockHash>) -> Result<Address> {
		let block = block.map(BlockId::Hash);
		self.contract
			.query("token", (), None, Options::default(), block)
			.await
			.map_err(Into::into)
	}

	/// Get the balance of an account.
	pub async fn balance(&self, owner: Address, block: Option<BlockHash>) -> Result<U256> {
		let block = block.map(BlockId::Hash);
		self.contract
			.query("balances", (owner,), None, Options::default(), block)
			.await
			.map_err(Into::into)
	}

	/// Retrieve the effective balance of an account.
	pub async fn effective_balance(
		&self,
		owner: Address,
		block: Option<BlockHash>,
	) -> Result<U256> {
		let block = block.map(BlockId::Hash);
		self.contract
			.query("effectiveBalance", (owner,), None, Options::default(), block)
			.await
			.map_err(Into::into)
	}

	/// Retrieve the total deposit of an account.
	pub async fn total_deposit(&self, owner: Address, block: Option<BlockHash>) -> Result<U256> {
		let block = block.map(BlockId::Hash);
		self.contract
			.query("total_deposit", (owner,), None, Options::default(), block)
			.await
			.map_err(Into::into)
	}

	/// Retrieve the whole balance of the user deposit contract.
	pub async fn whole_balance(&self, block: Option<BlockHash>) -> Result<U256> {
		let block = block.map(BlockId::Hash);
		self.contract
			.query("whole_balance", (), None, Options::default(), block)
			.await
			.map_err(Into::into)
	}

	/// Retrieve the limit of deposits the user deposit contract will manage.
	pub async fn whole_balance_limit(&self, block: Option<BlockHash>) -> Result<U256> {
		let block = block.map(BlockId::Hash);
		self.contract
			.query("whole_balance_limit", (), None, Options::default(), block)
			.await
			.map_err(Into::into)
	}

	/// Retrieve planned withdraw info.
	pub async fn withdraw_plan(
		&self,
		address: Address,
		block: Option<BlockHash>,
	) -> Result<WithdrawPlan> {
		let block = block.map(BlockId::Hash);
		let (withdraw_amount, withdraw_block): (TokenAmount, U256) = self
			.contract
			.query("withdraw_plans", (address,), None, Options::default(), block)
			.await?;

		Ok(WithdrawPlan { withdraw_amount, withdraw_block: withdraw_block.as_u64().into() })
	}

	/// Deposit an amount into user deposit.
	pub async fn deposit(
		&self,
		account: Account<T>,
		token_proxy: TokenProxy<T>,
		new_total_deposit: U256,
		block_hash: BlockHash,
	) -> Result<H256> {
		let lock = self.lock.write().await;
		let deposit_transaction = DepositTransaction {
			web3: self.web3.clone(),
			account: account.clone(),
			user_deposit: self.clone(),
			gas_metadata: self.gas_metadata.clone(),
			token: token_proxy.clone(),
		};

		let params = DepositTransactionParams { total_deposit: new_total_deposit };
		let result = deposit_transaction.execute(params, block_hash).await;
		drop(lock);
		result
	}

	/// Plan a withdraw from user deposit balance.
	pub async fn plan_withdraw(
		&self,
		account: Account<T>,
		amount: U256,
		block_hash: BlockHash,
	) -> Result<H256> {
		let lock = self.lock.write().await;
		let plan_withdraw_transaction = PlanWithdrawTransaction {
			web3: self.web3.clone(),
			account: account.clone(),
			user_deposit: self.clone(),
			gas_metadata: self.gas_metadata.clone(),
		};

		let params = PlanWithdrawTransactionParams { amount };
		let result = plan_withdraw_transaction.execute(params, block_hash).await;
		drop(lock);
		result
	}

	/// Actually withdraw amount from user deposit which was previously planned.
	pub async fn withdraw(
		&self,
		account: Account<T>,
		amount: U256,
		block_hash: BlockHash,
	) -> Result<H256> {
		let lock = self.lock.write().await;
		let withdraw_transaction = WithdrawTransaction {
			web3: self.web3.clone(),
			account: account.clone(),
			user_deposit: self.clone(),
			gas_metadata: self.gas_metadata.clone(),
		};

		let params = WithdrawTransactionParams { amount };
		let result = withdraw_transaction.execute(params, block_hash).await;
		drop(lock);
		result
	}
}