mpp 0.12.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Canonical first-party machine-token settlement routes.
//!
//! A machine-token payment approves the canonical swapper and calls `swapTo`
//! atomically. The merchant continues to receive the challenge currency while
//! the payer spends machineUSD.

use alloy::primitives::{address, Address, Bytes, TxKind, U256};
use alloy::providers::Provider;
use alloy::sol_types::SolCall;
use alloy::sol_types::SolValue;
use tempo_alloy::contracts::precompiles::ITIP20;
use tempo_alloy::primitives::transaction::Call;
use tempo_alloy::rpc::TempoTransactionRequest;

use super::{transfers::Transfer, CHAIN_ID, MODERATO_CHAIN_ID};

alloy::sol! {
    interface IMachineTokenSwapper {
        function swapTo(
            address inputToken,
            uint256 amount,
            address targetToken,
            address recipient,
            bytes32 memo
        ) external;

        struct ChannelDescriptor {
            address payer;
            address payee;
            address operator;
            address token;
            bytes32 salt;
            address authorizedSigner;
            bytes32 expiringNonceHash;
        }

        function settleSession(
            ChannelDescriptor calldata descriptor,
            address recipient,
            address targetToken,
            bytes32 routeSalt
        ) external;
    }
}

/// Resolve the canonical machine-token and swapper for a supported chain.
pub fn session_addresses(chain_id: u64) -> Option<(Address, Address)> {
    deployment(chain_id).map(|deployment| (deployment.token, deployment.swapper))
}

/// Bind a logical merchant settlement route into a TIP-1034 descriptor salt.
pub fn compute_session_salt(
    merchant: Address,
    target_token: Address,
    route_salt: alloy::primitives::B256,
) -> alloy::primitives::B256 {
    let typehash = alloy::primitives::keccak256(
        b"MachineUsdSessionRoute(address merchant,address targetToken,bytes32 routeSalt)",
    );
    alloy::primitives::keccak256((typehash, merchant, target_token, route_salt).abi_encode())
}

/// Encode a canonical machine-token session settlement call.
pub fn settle_session_call(
    chain_id: u64,
    descriptor: &super::session::ChannelDescriptor,
    route: &super::session::SettlementRoute,
) -> Result<Call, crate::error::MppError> {
    let (_, swapper) = session_addresses(chain_id).ok_or_else(|| {
        crate::error::MppError::InvalidConfig(format!(
            "machine tokens are not supported on chain ID {chain_id}"
        ))
    })?;
    let parse_address = |name: &str, value: &str| {
        value.parse::<Address>().map_err(|error| {
            crate::error::MppError::InvalidConfig(format!(
                "invalid session descriptor {name}: {error}"
            ))
        })
    };
    let parse_b256 = |name: &str, value: &str| {
        value.parse::<alloy::primitives::B256>().map_err(|error| {
            crate::error::MppError::InvalidConfig(format!(
                "invalid session descriptor {name}: {error}"
            ))
        })
    };
    if route.adapter.parse::<Address>().ok() != Some(swapper) {
        return Err(crate::error::MppError::InvalidConfig(
            "session settlement adapter is not canonical".into(),
        ));
    }
    let merchant = parse_address("settlement recipient", &route.recipient)?;
    let target_token = parse_address("settlement targetToken", &route.target_token)?;
    let route_salt = parse_b256("settlement routeSalt", &route.route_salt)?;
    let descriptor_salt = parse_b256("salt", &descriptor.salt)?;
    if descriptor_salt != compute_session_salt(merchant, target_token, route_salt) {
        return Err(crate::error::MppError::InvalidConfig(
            "session descriptor salt does not bind the settlement route".into(),
        ));
    }
    let descriptor = IMachineTokenSwapper::ChannelDescriptor {
        payer: parse_address("payer", &descriptor.payer)?,
        payee: parse_address("payee", &descriptor.payee)?,
        operator: parse_address("operator", &descriptor.operator)?,
        token: parse_address("token", &descriptor.token)?,
        salt: parse_b256("salt", &descriptor.salt)?,
        authorizedSigner: parse_address("authorizedSigner", &descriptor.authorized_signer)?,
        expiringNonceHash: parse_b256("expiringNonceHash", &descriptor.expiring_nonce_hash)?,
    };
    Ok(Call {
        to: TxKind::Call(swapper),
        value: U256::ZERO,
        input: Bytes::from(
            IMachineTokenSwapper::settleSessionCall {
                descriptor,
                recipient: merchant,
                targetToken: target_token,
                routeSalt: route_salt,
            }
            .abi_encode(),
        ),
    })
}

/// machineUSD on Tempo mainnet.
pub const MACHINE_TOKEN_MAINNET: Address = address!("20C0000000000000000000003793c39601711f19");
/// Canonical machineUSD swapper on Tempo mainnet.
pub const MACHINE_TOKEN_SWAPPER_MAINNET: Address =
    address!("C6D32f013E0fA3e83B63Dc680E99826761595732");
/// machineUSD on Tempo Moderato.
pub const MACHINE_TOKEN_TESTNET: Address = address!("20c000000000000000000000f85bbCa724044De0");
/// Canonical machineUSD swapper on Tempo Moderato.
pub const MACHINE_TOKEN_SWAPPER_TESTNET: Address =
    address!("07f1FE0467Ae01DE340024aa4b7DD9729b1c169b");

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Deployment {
    token: Address,
    swapper: Address,
}

/// The exact canonical calls and settlement sender for a machine-token payment.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MachineTokenRoute {
    /// `approve` followed by `swapTo`.
    pub calls: [Call; 2],
    /// The swapper that emits the merchant-facing TIP-20 transfer.
    pub settlement_sender: Address,
    /// The single merchant transfer settled by the route.
    pub transfer: Transfer,
}

fn deployment(chain_id: u64) -> Option<Deployment> {
    match chain_id {
        CHAIN_ID => Some(Deployment {
            token: MACHINE_TOKEN_MAINNET,
            swapper: MACHINE_TOKEN_SWAPPER_MAINNET,
        }),
        MODERATO_CHAIN_ID => Some(Deployment {
            token: MACHINE_TOKEN_TESTNET,
            swapper: MACHINE_TOKEN_SWAPPER_TESTNET,
        }),
        _ => None,
    }
}

/// Returns whether a canonical machine-token route exists on `chain_id`.
pub fn is_supported(chain_id: u64) -> bool {
    deployment(chain_id).is_some()
}

/// Returns the trusted settlement sender for a supported chain.
pub fn settlement_sender(chain_id: u64) -> Option<Address> {
    deployment(chain_id).map(|deployment| deployment.swapper)
}

/// Build the canonical route for a compatible charge.
///
/// The route intentionally supports exactly one memo-bearing transfer. Split
/// payments and unbound transfers fall back to ordinary funding behavior.
pub fn route(
    chain_id: u64,
    currency: Address,
    transfers: &[Transfer],
) -> Option<MachineTokenRoute> {
    let deployment = deployment(chain_id)?;
    let transfer = match transfers {
        [transfer] if transfer.memo.is_some() => transfer.clone(),
        _ => return None,
    };
    let memo = transfer.memo?;
    let approve = Call {
        to: TxKind::Call(deployment.token),
        value: U256::ZERO,
        input: Bytes::from(
            ITIP20::approveCall {
                spender: deployment.swapper,
                amount: transfer.amount,
            }
            .abi_encode(),
        ),
    };
    let swap = Call {
        to: TxKind::Call(deployment.swapper),
        value: U256::ZERO,
        input: Bytes::from(
            IMachineTokenSwapper::swapToCall {
                inputToken: deployment.token,
                amount: transfer.amount,
                targetToken: currency,
                recipient: transfer.recipient,
                memo: memo.into(),
            }
            .abi_encode(),
        ),
    };

    Some(MachineTokenRoute {
        calls: [approve, swap],
        settlement_sender: deployment.swapper,
        transfer,
    })
}

/// Match only the exact canonical route for a charge.
pub fn match_route(
    calls: &[Call],
    chain_id: u64,
    currency: Address,
    transfers: &[Transfer],
) -> Option<MachineTokenRoute> {
    let transfer = match transfers {
        [transfer] => transfer.clone(),
        _ => return None,
    };
    let swap = calls.get(1)?;
    let decoded = IMachineTokenSwapper::swapToCall::abi_decode_raw(swap.input.get(4..)?).ok()?;
    let mut transfer_with_memo = transfer;
    if transfer_with_memo.memo.is_none() {
        transfer_with_memo.memo = Some(decoded.memo.0);
    }
    let expected = route(chain_id, currency, &[transfer_with_memo])?;
    if calls == expected.calls.as_slice() {
        Some(expected)
    } else {
        None
    }
}

/// Prefer machine-token funding when the payer has sufficient balance and the
/// complete route simulates successfully. Any failure falls back to the
/// client's existing funding behavior.
pub async fn find_route<P: Provider<tempo_alloy::TempoNetwork>>(
    provider: &P,
    account: Address,
    chain_id: u64,
    currency: Address,
    transfers: &[Transfer],
) -> Option<MachineTokenRoute> {
    let route = route(chain_id, currency, transfers)?;
    let token = match route.calls[0].to {
        TxKind::Call(token) => token,
        TxKind::Create => return None,
    };
    let balance = ITIP20::new(token, provider)
        .balanceOf(account)
        .call()
        .await
        .ok()?;
    if balance < route.transfer.amount {
        return None;
    }

    let mut request = TempoTransactionRequest {
        calls: route.calls.to_vec(),
        ..Default::default()
    };
    request.inner.from = Some(account);
    request.inner.chain_id = Some(chain_id);
    provider.call(request).await.ok()?;
    Some(route)
}

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

    fn transfer() -> Transfer {
        Transfer {
            amount: U256::from(1_000_000),
            recipient: Address::repeat_byte(0x22),
            memo: Some([0xab; 32]),
        }
    }

    #[test]
    fn builds_and_matches_exact_canonical_route() {
        let currency = Address::repeat_byte(0x33);
        let route = route(MODERATO_CHAIN_ID, currency, &[transfer()]).unwrap();

        assert_eq!(route.calls[0].to, TxKind::Call(MACHINE_TOKEN_TESTNET));
        assert_eq!(
            route.calls[1].to,
            TxKind::Call(MACHINE_TOKEN_SWAPPER_TESTNET)
        );
        assert_eq!(
            match_route(&route.calls, MODERATO_CHAIN_ID, currency, &[transfer()]),
            Some(route.clone())
        );

        let approve = ITIP20::approveCall::abi_decode_raw(&route.calls[0].input[4..]).unwrap();
        assert_eq!(approve.spender, MACHINE_TOKEN_SWAPPER_TESTNET);
        assert_eq!(approve.amount, U256::from(1_000_000));
        let swap =
            IMachineTokenSwapper::swapToCall::abi_decode_raw(&route.calls[1].input[4..]).unwrap();
        assert_eq!(swap.inputToken, MACHINE_TOKEN_TESTNET);
        assert_eq!(swap.targetToken, currency);
        assert_eq!(swap.recipient, Address::repeat_byte(0x22));
    }

    #[test]
    fn rejects_mutated_and_incompatible_routes() {
        let currency = Address::repeat_byte(0x33);
        let canonical = route(MODERATO_CHAIN_ID, currency, &[transfer()]).unwrap();
        let mut mutated = canonical.calls.to_vec();
        mutated[0].value = U256::from(1);

        assert!(match_route(&mutated, MODERATO_CHAIN_ID, currency, &[transfer()]).is_none());
        assert!(route(1, currency, &[transfer()]).is_none());
        assert!(route(MODERATO_CHAIN_ID, currency, &[]).is_none());
        let mut without_memo = transfer();
        without_memo.memo = None;
        assert!(route(MODERATO_CHAIN_ID, currency, &[without_memo]).is_none());
        assert!(route(MODERATO_CHAIN_ID, currency, &[transfer(), transfer()]).is_none());
    }

    #[test]
    fn encodes_session_settlement_with_the_full_bound_descriptor() {
        let descriptor = super::super::session::ChannelDescriptor {
            payer: Address::repeat_byte(0x11).to_string(),
            payee: MACHINE_TOKEN_SWAPPER_TESTNET.to_string(),
            operator: Address::repeat_byte(0x22).to_string(),
            token: MACHINE_TOKEN_TESTNET.to_string(),
            salt: alloy::primitives::B256::repeat_byte(0x33).to_string(),
            authorized_signer: Address::repeat_byte(0x44).to_string(),
            expiring_nonce_hash: alloy::primitives::B256::repeat_byte(0x55).to_string(),
        };
        let route = super::super::session::SettlementRoute {
            adapter: MACHINE_TOKEN_SWAPPER_TESTNET.to_string(),
            recipient: Address::repeat_byte(0x22).to_string(),
            target_token: Address::repeat_byte(0x66).to_string(),
            route_salt: alloy::primitives::B256::repeat_byte(0x77).to_string(),
        };
        let expected_salt = compute_session_salt(
            Address::repeat_byte(0x22),
            Address::repeat_byte(0x66),
            alloy::primitives::B256::repeat_byte(0x77),
        );
        let descriptor = super::super::session::ChannelDescriptor {
            salt: expected_salt.to_string(),
            ..descriptor
        };
        let call = settle_session_call(MODERATO_CHAIN_ID, &descriptor, &route).unwrap();

        assert_eq!(call.to, TxKind::Call(MACHINE_TOKEN_SWAPPER_TESTNET));
        let decoded = IMachineTokenSwapper::settleSessionCall::abi_decode(&call.input).unwrap();
        assert_eq!(decoded.descriptor.payee, MACHINE_TOKEN_SWAPPER_TESTNET);
        assert_eq!(decoded.descriptor.operator, Address::repeat_byte(0x22));
        assert_eq!(decoded.descriptor.token, MACHINE_TOKEN_TESTNET);
        assert_eq!(decoded.recipient, Address::repeat_byte(0x22));
        assert_eq!(decoded.targetToken, Address::repeat_byte(0x66));
    }

    #[test]
    fn rejects_session_settlement_on_an_unsupported_chain() {
        let descriptor = super::super::session::ChannelDescriptor {
            payer: Address::ZERO.to_string(),
            payee: Address::ZERO.to_string(),
            operator: Address::ZERO.to_string(),
            token: Address::ZERO.to_string(),
            salt: alloy::primitives::B256::ZERO.to_string(),
            authorized_signer: Address::ZERO.to_string(),
            expiring_nonce_hash: alloy::primitives::B256::ZERO.to_string(),
        };
        let route = super::super::session::SettlementRoute {
            adapter: Address::ZERO.to_string(),
            recipient: Address::ZERO.to_string(),
            target_token: Address::ZERO.to_string(),
            route_salt: alloy::primitives::B256::ZERO.to_string(),
        };
        assert!(settle_session_call(1, &descriptor, &route).is_err());
    }

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

        let asserter = Asserter::new();
        asserter.push_success(&Bytes::from(ITIP20::balanceOfCall::abi_encode_returns(
            &U256::from(1_000_000),
        )));
        asserter.push_success(&Bytes::new());
        let provider = ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_mocked_client(asserter);

        let found = find_route(
            &provider,
            Address::repeat_byte(0x11),
            MODERATO_CHAIN_ID,
            Address::repeat_byte(0x33),
            &[transfer()],
        )
        .await;

        assert!(found.is_some());
    }

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

        let asserter = Asserter::new();
        asserter.push_success(&Bytes::from(ITIP20::balanceOfCall::abi_encode_returns(
            &U256::from(999_999),
        )));
        let provider = ProviderBuilder::new_with_network::<tempo_alloy::TempoNetwork>()
            .connect_mocked_client(asserter);

        let found = find_route(
            &provider,
            Address::repeat_byte(0x11),
            MODERATO_CHAIN_ID,
            Address::repeat_byte(0x33),
            &[transfer()],
        )
        .await;

        assert!(found.is_none());
    }
}