forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
323 lines (294 loc) · 10.6 KB
/
Copy pathlib.rs
File metadata and controls
323 lines (294 loc) · 10.6 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
//! # Path Payment Contract
//!
//! Automatic currency conversion using path payments: find paths, get rates,
//! execute multi-hop conversions with slippage protection.
#![no_std]
use soroban_sdk::{
contract, contractimpl, symbol_short, token, Address, Env, IntoVal, String, Symbol, Vec,
};
mod events;
mod storage;
mod types;
#[cfg(test)]
mod test;
use crate::types::{Asset, Error};
/// Maximum path length (number of hops + 1 = number of assets in path).
const MAX_PATH_LEN: u32 = 6;
#[contract]
pub struct PathPaymentContract;
#[contractimpl]
impl PathPaymentContract {
/// Initialize with an admin. Admin can register pairs and set swap router.
pub fn initialize(env: Env, admin: Address) -> Result<(), Error> {
if storage::is_initialized(&env) {
return Err(Error::NotInitialized); // already initialized
}
admin.require_auth();
storage::set_admin(&env, &admin);
storage::set_initialized(&env);
events::emit_initialized(&env, &admin);
Ok(())
}
/// Register a directed pair (from_asset -> to_asset) for path finding.
pub fn register_pair(env: Env, from_asset: Asset, to_asset: Asset) -> Result<(), Error> {
storage::get_admin(&env).require_auth();
if !storage::is_initialized(&env) {
return Err(Error::NotInitialized);
}
let from = from_asset.address();
let to = to_asset.address();
storage::add_pair(&env, from, to);
events::emit_pair_registered(&env, from, to);
Ok(())
}
/// Set conversion rate: amount of to_asset per 1e7 units of from_asset.
pub fn set_rate(env: Env, from_asset: Asset, to_asset: Asset, rate: i128) -> Result<(), Error> {
storage::get_admin(&env).require_auth();
if !storage::is_initialized(&env) {
return Err(Error::NotInitialized);
}
storage::set_rate(&env, from_asset.address(), to_asset.address(), rate);
Ok(())
}
/// Set the swap router contract. Router must implement: swap(from, to, amount_in) -> i128.
pub fn set_swap_router(env: Env, router: Address) -> Result<(), Error> {
storage::get_admin(&env).require_auth();
if !storage::is_initialized(&env) {
return Err(Error::NotInitialized);
}
storage::set_swap_router(&env, &router);
Ok(())
}
/// Find a payment path from source_asset to dest_asset using registered pairs (BFS).
/// Returns path as [source_asset, ..., dest_asset] or Error::PathNotFound.
pub fn find_payment_path(
env: Env,
source_asset: Asset,
dest_asset: Asset,
_amount: i128,
) -> Result<Vec<Asset>, Error> {
if !storage::is_initialized(&env) {
return Err(Error::NotInitialized);
}
let source = source_asset.address().clone();
let dest = dest_asset.address().clone();
if source == dest {
let mut path = Vec::new(&env);
path.push_back(source_asset);
return Ok(path);
}
let pairs = storage::get_pair_list(&env);
let mut queue = Vec::new(&env);
queue.push_back(source.clone());
let mut visited = Vec::new(&env);
visited.push_back(source.clone());
let mut parent: Vec<(Address, Address)> = Vec::new(&env);
let mut found = false;
let mut front = 0u32;
while front < queue.len() {
let current = queue.get(front).unwrap();
front += 1;
if current == dest {
found = true;
break;
}
for i in 0..pairs.len() {
let pair = pairs.get(i).unwrap();
if pair.from == current {
let to = pair.to.clone();
if !Self::vec_contains_address(&visited, &to) {
visited.push_back(to.clone());
parent.push_back((to.clone(), current.clone()));
queue.push_back(to);
}
}
}
}
if !found {
return Err(Error::PathNotFound);
}
// Reconstruct path from dest to source
let mut path_rev = Vec::new(&env);
path_rev.push_back(dest.clone());
let mut cur = dest.clone();
while cur != source {
let p = Self::find_parent(&parent, &cur).ok_or(Error::PathNotFound)?;
path_rev.push_back(p.clone());
cur = p;
}
// Reverse to get source -> dest
let mut path = Vec::new(&env);
for i in (0..path_rev.len()).rev() {
path.push_back(Asset(path_rev.get(i).unwrap()));
}
if path.len() > MAX_PATH_LEN {
return Err(Error::InvalidPath);
}
events::emit_path_found(&env, &source, &dest, &path);
Ok(path)
}
/// Get conversion rate from from_asset to to_asset (amount of to per 1e7 of from).
/// Returns 0 if same asset or rate not set.
pub fn get_conversion_rate(env: Env, from_asset: Asset, to_asset: Asset) -> i128 {
if !storage::is_initialized(&env) {
return 0;
}
let from = from_asset.address();
let to = to_asset.address();
if from == to {
return 10_000_000_i128; // 1:1 in 7 decimals
}
storage::get_rate(&env, from, to).unwrap_or(0)
}
/// Execute path payment: pull source amount from caller, convert along path, enforce max_slippage.
/// split_id: identifier for the split (for event/logging).
/// path: [source_asset, ..., dest_asset].
/// amount_in: amount of path[0] to pull from caller (caller must approve).
/// max_slippage: basis points (e.g. 100 = 1%). Returns amount of dest_asset received.
/// Caller must authorize and approve transfer of amount_in of path[0].
pub fn execute_path_payment(
env: Env,
caller: Address,
split_id: String,
path: Vec<Asset>,
amount_in: i128,
max_slippage: u32,
) -> Result<i128, Error> {
Self::execute_path_payment_internal(env, caller, split_id, path, amount_in, max_slippage)
}
fn execute_path_payment_internal(
env: Env,
caller: Address,
split_id: String,
path: Vec<Asset>,
amount_in: i128,
max_slippage: u32,
) -> Result<i128, Error> {
caller.require_auth();
if !storage::is_initialized(&env) {
return Err(Error::NotInitialized);
}
if path.is_empty() {
return Err(Error::InvalidPath);
}
if path.len() > MAX_PATH_LEN {
return Err(Error::InvalidPath);
}
if amount_in <= 0 {
return Err(Error::InvalidAmount);
}
let source = path.get(0).unwrap();
let dest = path.get(path.len() - 1).unwrap();
let source_addr = source.address().clone();
let dest_addr = dest.address().clone();
let expected_dest = Self::simulate_path_amount(&env, &path, amount_in)?;
if expected_dest <= 0 {
return Err(Error::RateNotAvailable);
}
// min_dest with slippage: expected_dest * (10000 - max_slippage) / 10000
let min_dest = (expected_dest * (10000i128 - max_slippage as i128)) / 10000;
// Pull source from caller
let token_client = token::Client::new(&env, &source_addr);
token_client.transfer(&caller, &env.current_contract_address(), &amount_in);
let mut current_amount = amount_in;
let mut current_asset = source_addr.clone();
if path.len() == 1 {
// Same asset: no conversion, just pull and report
events::emit_path_payment_executed(
&env,
&split_id,
&source_addr,
&dest_addr,
current_amount,
1,
);
return Ok(current_amount);
}
let router = storage::get_swap_router(&env).ok_or(Error::SwapFailed)?;
for i in 0..path.len() - 1 {
let to_asset = path.get(i + 1).unwrap();
let to_addr = to_asset.address().clone();
let amount_out =
Self::invoke_swap(&env, &router, ¤t_asset, &to_addr, current_amount)?;
if amount_out <= 0 {
return Err(Error::SwapFailed);
}
current_amount = amount_out;
current_asset = to_addr;
}
if current_amount < min_dest {
return Err(Error::SlippageExceeded);
}
events::emit_path_payment_executed(
&env,
&split_id,
&source_addr,
&dest_addr,
current_amount,
path.len(),
);
Ok(current_amount)
}
pub fn get_admin(env: Env) -> Address {
storage::get_admin(&env)
}
pub fn get_swap_router(env: Env) -> Option<Address> {
storage::get_swap_router(&env)
}
}
impl PathPaymentContract {
fn vec_contains_address(v: &Vec<Address>, a: &Address) -> bool {
for i in 0..v.len() {
if v.get(i).unwrap() == *a {
return true;
}
}
false
}
fn find_parent(parent: &Vec<(Address, Address)>, node: &Address) -> Option<Address> {
for i in 0..parent.len() {
let (n, p) = parent.get(i).unwrap();
if n == *node {
return Some(p);
}
}
None
}
/// Simulate conversion along path for a given input amount; returns expected output.
fn simulate_path_amount(env: &Env, path: &Vec<Asset>, amount_in: i128) -> Result<i128, Error> {
if path.is_empty() {
return Err(Error::InvalidPath);
}
if path.len() == 1 {
return Ok(amount_in);
}
let mut amount = amount_in;
for i in 0..path.len() - 1 {
let from_asset = path.get(i).unwrap();
let to_asset = path.get(i + 1).unwrap();
let from = from_asset.address().clone();
let to = to_asset.address().clone();
let rate = storage::get_rate(env, &from, &to).ok_or(Error::RateNotAvailable)?;
amount = (amount * rate) / 10_000_000;
if amount <= 0 {
return Err(Error::RateNotAvailable);
}
}
Ok(amount)
}
fn invoke_swap(
env: &Env,
router: &Address,
from: &Address,
to: &Address,
amount: i128,
) -> Result<i128, Error> {
let swap_sym: Symbol = symbol_short!("swap");
let result: i128 = env.invoke_contract(
router,
&swap_sym,
(from.clone(), to.clone(), amount).into_val(env),
);
Ok(result)
}
}