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)]
33pub enum Balance {
34 Perp(String),
37 Spot(u32),
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum Change {
45 Up(Dec),
47 Down(Dec),
49 DownAtLeast(Dec),
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct Effect {
57 pub balance: Balance,
59 pub change: Change,
61}
62
63impl Effect {
64 #[must_use]
67 pub fn landed(&self, before: Dec, after: Dec) -> bool {
68 match self.change {
69 Change::Up(amount) => before.checked_add(amount) == Some(after),
70 Change::Down(amount) => before.checked_sub(amount) == Some(after),
71 Change::DownAtLeast(amount) => before.checked_sub(amount).is_some_and(|most| after <= most),
72 }
73 }
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct Plan<A> {
79 pub network: Network,
81 pub action: A,
83 pub nonce: u64,
85 pub key: Signers,
87 pub effect: Effect,
89}
90
91#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
93pub enum Refused {
94 #[error("a pooled account holds USDC in one balance, so there is nothing to move between {0}")]
96 OneBalance(&'static str),
97 #[error("the two balances are the same one")]
99 SameDex,
100 #[error("that is this account; a send goes somewhere else")]
102 ToSelf,
103 #[error("{0} is a system address: a send there crosses to HyperEVM, which `to_evm` plans")]
106 SystemAddress(Address),
107 #[error("{0} has no token on HyperEVM to cross to")]
109 NotLinked(String),
110 #[error("USDC does not cross to HyperEVM here")]
112 Usdc,
113 #[error("{amount} has more than {places} decimal places")]
115 TooFine {
116 amount: Dec,
118 places: u32,
120 },
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub struct Ctx {
126 pub network: Network,
128 pub account: Address,
130 pub keeping: Keeping,
132 pub nonce: u64,
134}
135
136impl Ctx {
137 #[must_use]
140 pub fn usdc(&self) -> Balance {
141 match self.keeping.pools() {
142 true => Balance::Spot(USDC_INDEX),
143 false => Balance::Perp(PERP_DEX.to_owned()),
144 }
145 }
146
147 const fn plan<A>(&self, action: A, key: Signers, effect: Effect) -> Plan<A> {
148 Plan { network: self.network, action, nonce: self.nonce, key, effect }
149 }
150
151 pub fn class_transfer(&self, amount: Amount, to_perp: bool) -> Result<Plan<UsdClassTransfer>, Refused> {
154 if self.keeping.pools() {
155 return Err(Refused::OneBalance("perps and spot"));
156 }
157 let value = places(&amount, USDC_DECIMALS)?;
158 let change = match to_perp {
159 true => Change::Up(value),
160 false => Change::Down(value),
161 };
162 let effect = Effect { balance: Balance::Perp(PERP_DEX.to_owned()), change };
163 Ok(self.plan(UsdClassTransfer::new(amount, to_perp, self.nonce), UsdClassTransfer::KEY, effect))
164 }
165
166 pub fn usd_send(&self, to: Address, amount: Amount) -> Result<Plan<UsdSend>, Refused> {
168 self.recipient(to)?;
169 let value = places(&amount, USDC_DECIMALS)?;
170 let effect = Effect { balance: self.usdc(), change: Change::DownAtLeast(value) };
171 Ok(self.plan(UsdSend::new(to, amount, self.nonce), UsdSend::KEY, effect))
172 }
173
174 pub fn send_token(&self, to: Address, token: &SpotToken, amount: Amount) -> Result<Plan<SpotOut>, Refused> {
176 self.recipient(to)?;
177 let value = places(&amount, token.wei_decimals)?;
178 let effect = Effect { balance: Balance::Spot(token.index), change: Change::DownAtLeast(value) };
179 let action = SpotOut::new(to, &token.wire(), amount, self.keeping, self.nonce);
180 Ok(self.plan(action, SpotOut::KEY, effect))
181 }
182
183 pub fn to_evm(&self, token: &SpotToken, amount: Amount) -> Result<Plan<SpotOut>, Refused> {
186 if token.index == USDC_INDEX {
187 return Err(Refused::Usdc);
188 }
189 let most = token.crossing_places(self.network).ok_or_else(|| Refused::NotLinked(token.name.clone()))?;
190 let value = places(&amount, most)?;
191 let effect = Effect { balance: Balance::Spot(token.index), change: Change::DownAtLeast(value) };
192 let action = SpotOut::new(token.system_address(self.network), &token.wire(), amount, self.keeping, self.nonce);
193 Ok(self.plan(action, SpotOut::KEY, effect))
194 }
195
196 pub fn between(&self, from: &str, to: &str, token: &SpotToken, amount: Amount) -> Result<Plan<SendAsset>, Refused> {
200 let effect = self.between_effect(from, to, token, &amount)?;
201 let action = SendAsset::new(self.account, from, to, &token.wire(), amount, self.nonce);
202 Ok(self.plan(action, SendAsset::KEY, effect))
203 }
204
205 pub fn agent_between(
207 &self,
208 from: &str,
209 to: &str,
210 token: &SpotToken,
211 amount: Amount,
212 ) -> Result<Plan<AgentSendAsset>, Refused> {
213 let effect = self.between_effect(from, to, token, &amount)?;
214 let action = AgentSendAsset::new(self.account, from, to, &token.wire(), amount, self.nonce);
215 Ok(self.plan(action, AgentSendAsset::KEY, effect))
216 }
217
218 pub fn withdraw(&self, to: Address, amount: Amount) -> Result<Plan<Withdraw3>, Refused> {
221 if is_system_address(to) {
222 return Err(Refused::SystemAddress(to));
223 }
224 let value = places(&amount, USDC_DECIMALS)?;
225 let effect = Effect { balance: self.usdc(), change: Change::Down(value) };
226 Ok(self.plan(Withdraw3::new(to, amount, self.nonce), Withdraw3::KEY, effect))
227 }
228
229 fn recipient(&self, to: Address) -> Result<(), Refused> {
230 match (to == self.account, is_system_address(to)) {
231 (true, _) => Err(Refused::ToSelf),
232 (false, true) => Err(Refused::SystemAddress(to)),
233 (false, false) => Ok(()),
234 }
235 }
236
237 fn between_effect(&self, from: &str, to: &str, token: &SpotToken, amount: &Amount) -> Result<Effect, Refused> {
240 if self.keeping.pools() {
241 return Err(Refused::OneBalance("dexes"));
242 }
243 if from == to {
244 return Err(Refused::SameDex);
245 }
246 let value = places(amount, token.wei_decimals.min(USDC_DECIMALS))?;
247 let balance = match from {
248 SPOT_DEX => Balance::Spot(token.index),
249 dex => Balance::Perp(dex.to_owned()),
250 };
251 Ok(Effect { balance, change: Change::Down(value) })
252 }
253}
254
255fn places(amount: &Amount, most: u32) -> Result<Dec, Refused> {
257 let value = amount.value();
258 match value.places() > most {
259 true => Err(Refused::TooFine { amount: value, places: most }),
260 false => Ok(value),
261 }
262}
263
264#[cfg(test)]
265#[path = "tests/plan.rs"]
266mod tests;