1use crate::account::{ActionKind, Keeping, Signers};
6use crate::client::{Network, USDC_INDEX};
7use crate::transfer::evm::is_system_address;
8use crate::transfer::send::actions::{
9 AgentSendAsset, PERP_DEX, SPOT_DEX, SendAsset, SpotOut, UsdClassTransfer, UsdSend, Withdraw3,
10};
11use crate::transfer::send::amount::Amount;
12use crate::transfer::send::token::SpotToken;
13use crate::utils::{Address, Dec, USDC_DECIMALS};
14
15const KINDS: [ActionKind; 6] = [
17 ActionKind::UsdClassTransfer,
18 ActionKind::UsdSend,
19 ActionKind::SpotSend,
20 ActionKind::SendAsset,
21 ActionKind::Withdraw3,
22 ActionKind::AgentSendAsset,
23];
24
25#[must_use]
27pub fn key(kind: &str) -> Option<Signers> {
28 ActionKind::from_wire(kind).filter(|kind| KINDS.contains(kind)).map(ActionKind::signers)
29}
30
31#[derive(Debug, Clone, PartialEq, Eq, Hash)]
33#[non_exhaustive]
34pub enum Balance {
35 Perp(String),
38 Spot(u32),
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45#[non_exhaustive]
46pub enum Change {
47 Up(Dec),
49 Down(Dec),
51 DownAtLeast(Dec),
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
58#[non_exhaustive]
59pub struct Effect {
60 pub balance: Balance,
62 pub change: Change,
64}
65
66impl Effect {
67 #[must_use]
70 pub fn landed(&self, before: Dec, after: Dec) -> bool {
71 match self.change {
72 Change::Up(amount) => before.checked_add(amount) == Some(after),
73 Change::Down(amount) => before.checked_sub(amount) == Some(after),
74 Change::DownAtLeast(amount) => before.checked_sub(amount).is_some_and(|most| after <= most),
75 }
76 }
77}
78
79#[derive(Debug, Clone, PartialEq, Eq)]
81#[non_exhaustive]
82pub struct Plan<A> {
83 pub network: Network,
85 pub action: A,
87 pub nonce: u64,
89 pub key: Signers,
91 pub effect: Effect,
93}
94
95#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
97#[non_exhaustive]
98pub enum Refused {
99 #[error("a pooled account holds USDC in one balance, so there is nothing to move between {0}")]
101 OneBalance(&'static str),
102 #[error("the two balances are the same one")]
104 SameDex,
105 #[error("that is this account; a send goes somewhere else")]
107 ToSelf,
108 #[error("{0} is a system address: a send there crosses to HyperEVM, which `to_evm` plans")]
111 SystemAddress(Address),
112 #[error("{0} has no token on HyperEVM to cross to")]
114 NotLinked(String),
115 #[error("USDC does not cross to HyperEVM here")]
117 Usdc,
118 #[error("{amount} has more than {places} decimal places")]
120 TooFine {
121 amount: Dec,
123 places: u32,
125 },
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub struct Ctx {
131 pub network: Network,
133 pub account: Address,
135 pub keeping: Keeping,
137 pub nonce: u64,
139}
140
141impl Ctx {
142 #[must_use]
145 pub fn usdc(&self) -> Balance {
146 match self.keeping.pools() {
147 true => Balance::Spot(USDC_INDEX),
148 false => Balance::Perp(PERP_DEX.to_owned()),
149 }
150 }
151
152 const fn plan<A>(&self, action: A, key: Signers, effect: Effect) -> Plan<A> {
153 Plan { network: self.network, action, nonce: self.nonce, key, effect }
154 }
155
156 pub fn class_transfer(&self, amount: Amount, to_perp: bool) -> Result<Plan<UsdClassTransfer>, Refused> {
159 if self.keeping.pools() {
160 return Err(Refused::OneBalance("perps and spot"));
161 }
162 let value = places(&amount, USDC_DECIMALS)?;
163 let change = match to_perp {
164 true => Change::Up(value),
165 false => Change::Down(value),
166 };
167 let effect = Effect { balance: Balance::Perp(PERP_DEX.to_owned()), change };
168 Ok(self.plan(UsdClassTransfer::new(amount, to_perp, self.nonce), UsdClassTransfer::KEY, effect))
169 }
170
171 pub fn usd_send(&self, to: Address, amount: Amount) -> Result<Plan<UsdSend>, Refused> {
173 self.recipient(to)?;
174 let value = places(&amount, USDC_DECIMALS)?;
175 let effect = Effect { balance: self.usdc(), change: Change::DownAtLeast(value) };
176 Ok(self.plan(UsdSend::new(to, amount, self.nonce), UsdSend::KEY, effect))
177 }
178
179 pub fn send_token(&self, to: Address, token: &SpotToken, amount: Amount) -> Result<Plan<SpotOut>, Refused> {
181 self.recipient(to)?;
182 let value = places(&amount, token.wei_decimals)?;
183 let effect = Effect { balance: Balance::Spot(token.index), change: Change::DownAtLeast(value) };
184 let action = SpotOut::new(to, &token.wire(), amount, self.keeping, self.nonce);
185 Ok(self.plan(action, SpotOut::KEY, effect))
186 }
187
188 pub fn to_evm(&self, token: &SpotToken, amount: Amount) -> Result<Plan<SpotOut>, Refused> {
191 if token.index == USDC_INDEX {
192 return Err(Refused::Usdc);
193 }
194 let most = token.crossing_places(self.network).ok_or_else(|| Refused::NotLinked(token.name.clone()))?;
195 let value = places(&amount, most)?;
196 let effect = Effect { balance: Balance::Spot(token.index), change: Change::DownAtLeast(value) };
197 let action = SpotOut::new(token.system_address(self.network), &token.wire(), amount, self.keeping, self.nonce);
198 Ok(self.plan(action, SpotOut::KEY, effect))
199 }
200
201 pub fn between(&self, from: &str, to: &str, token: &SpotToken, amount: Amount) -> Result<Plan<SendAsset>, Refused> {
205 let effect = self.between_effect(from, to, token, &amount)?;
206 let action = SendAsset::new(self.account, from, to, &token.wire(), amount, self.nonce);
207 Ok(self.plan(action, SendAsset::KEY, effect))
208 }
209
210 pub fn agent_between(
212 &self,
213 from: &str,
214 to: &str,
215 token: &SpotToken,
216 amount: Amount,
217 ) -> Result<Plan<AgentSendAsset>, Refused> {
218 let effect = self.between_effect(from, to, token, &amount)?;
219 let action = AgentSendAsset::new(self.account, from, to, &token.wire(), amount, self.nonce);
220 Ok(self.plan(action, AgentSendAsset::KEY, effect))
221 }
222
223 pub fn withdraw(&self, to: Address, amount: Amount) -> Result<Plan<Withdraw3>, Refused> {
226 if is_system_address(to) {
227 return Err(Refused::SystemAddress(to));
228 }
229 let value = places(&amount, USDC_DECIMALS)?;
230 let effect = Effect { balance: self.usdc(), change: Change::Down(value) };
231 Ok(self.plan(Withdraw3::new(to, amount, self.nonce), Withdraw3::KEY, effect))
232 }
233
234 fn recipient(&self, to: Address) -> Result<(), Refused> {
235 match (to == self.account, is_system_address(to)) {
236 (true, _) => Err(Refused::ToSelf),
237 (false, true) => Err(Refused::SystemAddress(to)),
238 (false, false) => Ok(()),
239 }
240 }
241
242 fn between_effect(&self, from: &str, to: &str, token: &SpotToken, amount: &Amount) -> Result<Effect, Refused> {
245 if self.keeping.pools() {
246 return Err(Refused::OneBalance("dexes"));
247 }
248 if from == to {
249 return Err(Refused::SameDex);
250 }
251 let value = places(amount, token.wei_decimals.min(USDC_DECIMALS))?;
252 let balance = match from {
253 SPOT_DEX => Balance::Spot(token.index),
254 dex => Balance::Perp(dex.to_owned()),
255 };
256 Ok(Effect { balance, change: Change::Down(value) })
257 }
258}
259
260fn places(amount: &Amount, most: u32) -> Result<Dec, Refused> {
262 let value = amount.value();
263 match value.places() > most {
264 true => Err(Refused::TooFine { amount: value, places: most }),
265 false => Ok(value),
266 }
267}
268
269#[cfg(test)]
270#[path = "tests/plan.rs"]
271mod tests;