mpp 0.16.0

Rust SDK for the Machine Payments Protocol (MPP)
Documentation
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Autoswap support for Tempo MPP payments.
//!
//! When a payment challenge requires a currency the client doesn't hold,
//! this module prepends a DEX swap call to the transaction so the user
//! automatically acquires the required token via the Tempo Stablecoin DEX.
//!
//! # How it works
//!
//! 1. Check the client's balance of the challenge currency
//! 2. If balance >= amount, no swap needed — proceed normally
//! 3. If balance < amount, query the DEX for an exact-output quote
//! 4. Prepend `approve` and `swapExactAmountOut` calls to the transaction
//!    so the swap and transfer execute atomically in a single AA transaction
//!
//! # Example
//!
//! ```ignore
//! use mpp::client::TempoProvider;
//!
//! let provider = TempoProvider::new(signer, "https://rpc.moderato.tempo.xyz")?
//!     .with_autoswap(AutoswapConfig {
//!         token_in: "0x20C000000000000000000000b9537d11c60E8b50".parse()?,
//!         slippage_bps: 100, // 1%
//!         max_amount_in: Some(1_010_000), // explicit input-token budget
//!     });
//! ```

use alloy::primitives::{Address, Bytes, TxKind, U256};
use alloy::sol_types::SolCall;
use tempo_alloy::contracts::precompiles::{
    IStablecoinDEX, ITIP20, STABLECOIN_DEX_ADDRESS as DEX_ADDRESS,
};
use tempo_alloy::primitives::transaction::Call;

use crate::error::{MppError, ResultExt};

/// Maximum allowed slippage in basis points (50% = 5000 bps).
const MAX_SLIPPAGE_BPS: u16 = 5_000;

/// Configuration for automatic token swaps.
#[derive(Debug, Clone)]
pub struct AutoswapConfig {
    /// The token to swap from (the token the user holds).
    pub token_in: Address,
    /// Slippage tolerance in basis points (e.g., 100 = 1%).
    /// Applied on top of the quoted `amountIn` to protect against price movement.
    pub slippage_bps: u16,
    /// Maximum input-token units per swap. Defaults to the missing output amount
    /// plus slippage (1:1 token units). Set explicitly for non-parity pairs.
    pub max_amount_in: Option<u128>,
}

impl AutoswapConfig {
    /// Create a new autoswap config with the given input token and slippage.
    pub fn new(token_in: Address, slippage_bps: u16) -> Self {
        Self {
            token_in,
            slippage_bps,
            max_amount_in: None,
        }
    }
}

/// Default slippage: 1% (100 basis points).
pub const DEFAULT_SLIPPAGE_BPS: u16 = 100;

/// Query the user's balance of `currency` and determine if a swap is needed.
///
/// Returns `Some(deficit)` if the user needs more tokens, `None` if balance is sufficient.
pub async fn check_balance_deficit<P: alloy::providers::Provider<tempo_alloy::TempoNetwork>>(
    provider: &P,
    owner: Address,
    currency: Address,
    amount: U256,
) -> Result<Option<U256>, MppError> {
    let tip20 = ITIP20::new(currency, provider);
    let balance = tip20
        .balanceOf(owner)
        .call()
        .await
        .mpp_http("failed to query balance")?;

    if balance >= amount {
        Ok(None)
    } else {
        Ok(Some(amount - balance))
    }
}

/// Quote the DEX for the `amountIn` required to receive `amount_out` of `token_out`.
pub async fn quote_swap<P: alloy::providers::Provider<tempo_alloy::TempoNetwork>>(
    provider: &P,
    token_in: Address,
    token_out: Address,
    amount_out: u128,
) -> Result<u128, MppError> {
    let dex = IStablecoinDEX::new(DEX_ADDRESS, provider);
    let amount_in = dex
        .quoteSwapExactAmountOut(token_in, token_out, amount_out)
        .call()
        .await
        .mpp_http("DEX quote failed")?;

    Ok(amount_in)
}

/// Build the approval required by the Stablecoin DEX.
pub fn build_approve_call(token_in: Address, max_amount_in: u128) -> Call {
    Call {
        to: TxKind::Call(token_in),
        value: U256::ZERO,
        input: Bytes::from(
            ITIP20::approveCall::new((DEX_ADDRESS, U256::from(max_amount_in))).abi_encode(),
        ),
    }
}

/// Build the swap call to prepend to the transaction.
///
/// Applies slippage tolerance to the quoted `amount_in` to compute `max_amount_in`.
pub fn build_swap_call(
    token_in: Address,
    token_out: Address,
    amount_out: u128,
    quoted_amount_in: u128,
    slippage_bps: u16,
) -> Call {
    // max_amount_in = quoted_amount_in * (10000 + slippage_bps) / 10000
    let max_amount_in = (U256::from(quoted_amount_in)
        * U256::from(10_000u64 + u64::from(slippage_bps))
        / U256::from(10_000))
    .min(U256::from(u128::MAX))
    .to::<u128>();

    let swap_data = Bytes::from(
        IStablecoinDEX::swapExactAmountOutCall {
            tokenIn: token_in,
            tokenOut: token_out,
            amountOut: amount_out,
            maxAmountIn: max_amount_in,
        }
        .abi_encode(),
    );

    Call {
        to: TxKind::Call(DEX_ADDRESS),
        value: U256::ZERO,
        input: swap_data,
    }
}

/// Resolve autoswap: check balance, quote, and return the approval + swap calls if needed.
///
/// Returns `Ok(Some(calls))` if a swap is needed, `Ok(None)` if balance is sufficient.
///
/// Validates that:
/// 1. The slippage tolerance is within bounds
/// 2. The user has sufficient `token_in` balance to cover `max_amount_in`
pub async fn resolve_autoswap_calls<P: alloy::providers::Provider<tempo_alloy::TempoNetwork>>(
    provider: &P,
    owner: Address,
    currency: Address,
    amount: U256,
    config: &AutoswapConfig,
) -> Result<Option<Vec<Call>>, MppError> {
    if config.slippage_bps > MAX_SLIPPAGE_BPS {
        return Err(MppError::InvalidConfig(format!(
            "autoswap slippage {}bps exceeds maximum {}bps",
            config.slippage_bps, MAX_SLIPPAGE_BPS
        )));
    }

    if config.token_in == currency {
        // Already holding the right token — no swap needed.
        return Ok(None);
    }

    let deficit = match check_balance_deficit(provider, owner, currency, amount).await? {
        Some(deficit) => deficit,
        None => return Ok(None),
    };
    let amount_out: u128 = deficit
        .try_into()
        .map_err(|_| MppError::InvalidAmount(format!("deficit {deficit} exceeds u128")))?;

    let quoted_amount_in = quote_swap(provider, config.token_in, currency, amount_out).await?;

    // Compute max_amount_in with slippage and verify the user can cover it.
    let max_amount_in = bounded_swap_input(amount_out, quoted_amount_in, config)?;
    let required = U256::from(max_amount_in);
    if let Some(deficit) = check_balance_deficit(provider, owner, config.token_in, required).await?
    {
        return Err(MppError::from(
            crate::client::tempo::TempoClientError::InsufficientBalance {
                token: config.token_in.to_string(),
                available: (required - deficit).to_string(),
                required: max_amount_in.to_string(),
            },
        ));
    }

    Ok(Some(vec![
        build_approve_call(config.token_in, max_amount_in),
        build_swap_call(config.token_in, currency, amount_out, max_amount_in, 0),
    ]))
}

/// Bound spending independently of the DEX quote, using wide arithmetic to avoid overflow.
fn bounded_swap_input(
    amount_out: u128,
    quoted: u128,
    config: &AutoswapConfig,
) -> Result<u128, MppError> {
    let with_slippage = |amount: u128| {
        U256::from(amount) * U256::from(10_000u64 + u64::from(config.slippage_bps))
            / U256::from(10_000)
    };
    let limit = config
        .max_amount_in
        .map(U256::from)
        .unwrap_or_else(|| with_slippage(amount_out));
    if quoted == 0 || U256::from(quoted) > limit {
        return Err(MppError::InvalidAmount(
            "autoswap quote exceeds spend limit or is zero".into(),
        ));
    }
    with_slippage(quoted)
        .min(limit)
        .try_into()
        .map_err(|_| MppError::InvalidAmount("autoswap maximum input exceeds u128".into()))
}

/// Resolve the DEX swap call without its approval call.
///
/// This compatibility helper preserves the original API. Transaction builders
/// should use [`resolve_autoswap_calls`] so the DEX approval and swap execute
/// atomically in the correct order.
pub async fn resolve_autoswap<P: alloy::providers::Provider<tempo_alloy::TempoNetwork>>(
    provider: &P,
    owner: Address,
    currency: Address,
    amount: U256,
    config: &AutoswapConfig,
) -> Result<Option<Call>, MppError> {
    Ok(
        resolve_autoswap_calls(provider, owner, currency, amount, config)
            .await?
            .and_then(|mut calls| calls.pop()),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloy::primitives::address;

    #[test]
    fn test_independent_spend_limit() {
        for (quote, cap, expected) in [
            (100, None, Some(101)),
            (101, None, Some(101)),
            (102, None, None),
            (0, None, None),
            (500, Some(600), Some(505)),
            (500, Some(499), None),
        ] {
            let mut config = AutoswapConfig::new(Address::ZERO, 100);
            config.max_amount_in = cap;
            assert_eq!(bounded_swap_input(100, quote, &config).ok(), expected);
        }
        let config = AutoswapConfig::new(Address::ZERO, 100);
        assert!(bounded_swap_input(u128::MAX, u128::MAX, &config).is_err());
        let call = build_swap_call(Address::ZERO, Address::ZERO, 1, u128::MAX, 0);
        let decoded =
            IStablecoinDEX::swapExactAmountOutCall::abi_decode_raw(&call.input[4..]).unwrap();
        assert_eq!(decoded.maxAmountIn, u128::MAX);
    }

    #[test]
    fn test_autoswap_config_new() {
        let token = address!("0x20C000000000000000000000b9537d11c60E8b50");
        let config = AutoswapConfig::new(token, 50);
        assert_eq!(config.token_in, token);
        assert_eq!(config.slippage_bps, 50);
    }

    #[test]
    fn test_build_swap_call_slippage() {
        let token_in = address!("0x20C000000000000000000000b9537d11c60E8b50");
        let token_out = address!("0x20c0000000000000000000000000000000000000");

        let call = build_swap_call(token_in, token_out, 1_000_000, 1_000_000, 100);

        // max_amount_in = 1_000_000 * 10100 / 10000 = 1_010_000
        assert_eq!(call.to, TxKind::Call(DEX_ADDRESS));
        assert_eq!(call.value, U256::ZERO);

        // Verify the encoded call data decodes correctly.
        let decoded =
            IStablecoinDEX::swapExactAmountOutCall::abi_decode_raw(&call.input[4..]).unwrap();
        assert_eq!(decoded.tokenIn, token_in);
        assert_eq!(decoded.tokenOut, token_out);
        assert_eq!(decoded.amountOut, 1_000_000);
        assert_eq!(decoded.maxAmountIn, 1_010_000);
    }

    #[test]
    fn test_build_swap_call_zero_slippage() {
        let token_in = address!("0x20C000000000000000000000b9537d11c60E8b50");
        let token_out = address!("0x20c0000000000000000000000000000000000000");

        let call = build_swap_call(token_in, token_out, 500_000, 500_000, 0);
        let decoded =
            IStablecoinDEX::swapExactAmountOutCall::abi_decode_raw(&call.input[4..]).unwrap();
        assert_eq!(decoded.maxAmountIn, 500_000);
    }

    #[test]
    fn test_build_swap_call_high_slippage() {
        let token_in = address!("0x20C000000000000000000000b9537d11c60E8b50");
        let token_out = address!("0x20c0000000000000000000000000000000000000");

        // 5% slippage
        let call = build_swap_call(token_in, token_out, 1_000_000, 1_000_000, 500);
        let decoded =
            IStablecoinDEX::swapExactAmountOutCall::abi_decode_raw(&call.input[4..]).unwrap();
        assert_eq!(decoded.maxAmountIn, 1_050_000);
    }

    #[test]
    fn test_build_approve_call() {
        let token_in = address!("0x20c0000000000000000000000000000000000000");
        let call = build_approve_call(token_in, 5_050_500);

        assert_eq!(call.to, TxKind::Call(token_in));
        let decoded = ITIP20::approveCall::abi_decode_raw(&call.input[4..]).unwrap();
        assert_eq!(decoded.spender, DEX_ADDRESS);
        assert_eq!(decoded.amount, U256::from(5_050_500));
    }

    #[tokio::test]
    async fn test_resolve_autoswap_returns_approve_then_swap() {
        use alloy::{
            primitives::Bytes,
            providers::{mock::Asserter, ProviderBuilder},
        };

        let token_in = address!("0x20c0000000000000000000000000000000000000");
        let token_out = address!("0x20C000000000000000000000b9537d11c60E8b50");
        let asserter = Asserter::new();
        asserter.push_success(&Bytes::from(ITIP20::balanceOfCall::abi_encode_returns(
            &U256::from(52_906),
        )));
        asserter.push_success(&Bytes::from(
            IStablecoinDEX::quoteSwapExactAmountOutCall::abi_encode_returns(&4_947_094u128),
        ));
        asserter.push_success(&Bytes::from(ITIP20::balanceOfCall::abi_encode_returns(
            &U256::from(16_852_785),
        )));
        let provider = ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_mocked_client(asserter);

        let calls = resolve_autoswap_calls(
            &provider,
            Address::repeat_byte(0x11),
            token_out,
            U256::from(5_000_000),
            &AutoswapConfig::new(token_in, 100),
        )
        .await
        .unwrap()
        .unwrap();

        assert_eq!(calls.len(), 2);
        let approve = ITIP20::approveCall::abi_decode_raw(&calls[0].input[4..]).unwrap();
        assert_eq!(approve.spender, DEX_ADDRESS);
        assert_eq!(approve.amount, U256::from(4_996_564));
        let swap =
            IStablecoinDEX::swapExactAmountOutCall::abi_decode_raw(&calls[1].input[4..]).unwrap();
        assert_eq!(swap.amountOut, 4_947_094);
        assert_eq!(swap.maxAmountIn, 4_996_564);
    }

    #[tokio::test]
    async fn test_resolve_autoswap_reports_available_input_balance() {
        use alloy::{
            primitives::Bytes,
            providers::{mock::Asserter, ProviderBuilder},
        };

        let token_in = address!("0x20c0000000000000000000000000000000000000");
        let token_out = address!("0x20C000000000000000000000b9537d11c60E8b50");
        let asserter = Asserter::new();
        asserter.push_success(&Bytes::from(ITIP20::balanceOfCall::abi_encode_returns(
            &U256::ZERO,
        )));
        asserter.push_success(&Bytes::from(
            IStablecoinDEX::quoteSwapExactAmountOutCall::abi_encode_returns(&5_000_000u128),
        ));
        asserter.push_success(&Bytes::from(ITIP20::balanceOfCall::abi_encode_returns(
            &U256::from(3_000),
        )));
        let provider = ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_mocked_client(asserter);

        let err = resolve_autoswap_calls(
            &provider,
            Address::repeat_byte(0x11),
            token_out,
            U256::from(5_000_000),
            &AutoswapConfig::new(token_in, 100),
        )
        .await
        .unwrap_err();

        assert_eq!(
            err.to_string(),
            format!("Insufficient {token_in} balance: have 3000, need 5050000")
        );
    }
}