Skip to main content

taskfast_agent/
chain.rs

1// SPDX-License-Identifier: MIT
2//! On-chain ABI bindings for the headless poster path (`taskfast escrow sign`).
3//!
4//! Mirrors the JS wagmi bindings in `assets/js/escrow_sign.js` on the platform
5//! side. The two must stay byte-compatible: the Rust CLI pre-computes an
6//! `escrowId` that Solidity's `TaskEscrow.computeEscrowId` re-derives post
7//! transfer — any drift and the signature the poster pre-signed becomes
8//! unusable.
9//!
10//! # Fee-on-transfer caveat
11//!
12//! `TaskEscrow.open` computes its on-chain `escrowId` using `actualDeposit`
13//! (the post-transfer balance delta, not the supplied `deposit`). For a
14//! standard ERC-20 the two are equal, so the prediction matches. A
15//! fee-on-transfer token would diverge — callers rely on the platform's
16//! `allowedTokens` allowlist (fee-on-transfer excluded) to keep this safe.
17//!
18//! # Why a separate module (not folded into `signing.rs`)
19//!
20//! `signing.rs` is the EIP-712 typed-data surface (hash + sign primitives).
21//! These bindings are non-712: plain ABI `sol!` contract definitions used to
22//! encode calldata for `approve`/`open`. Keeping them separate keeps the
23//! signing module's scope tight and avoids pulling ERC-20 view calls into a
24//! crate section that shouldn't care about them.
25
26use alloy_primitives::{keccak256, Address, B256, U256};
27#[cfg(test)]
28use alloy_sol_types::SolCall;
29use alloy_sol_types::{sol, SolValue};
30
31sol! {
32    /// TaskEscrow contract surface used by the poster flow. Only the mutating
33    /// functions needed for `open` / `openWithMemo` are bound — full surface
34    /// lives in the platform's Solidity source.
35    #[allow(missing_docs)]
36    contract TaskEscrow {
37        function open(
38            address token,
39            uint256 deposit,
40            address worker,
41            uint256 platformFeeAmount,
42            address platform,
43            address arbitrator,
44            bytes32 salt
45        ) external returns (bytes32);
46
47        function openWithMemo(
48            address token,
49            uint256 deposit,
50            address worker,
51            uint256 platformFeeAmount,
52            address platform,
53            address arbitrator,
54            bytes32 salt,
55            bytes32 memoHash
56        ) external returns (bytes32);
57    }
58
59    /// Minimal ERC-20 surface needed to pre-flight the escrow deposit. Only
60    /// `approve`, `allowance`, and `balanceOf` are bound; `transfer` is
61    /// handled through the existing ERC-20 transfer helper in `tempo_rpc`.
62    #[allow(missing_docs)]
63    contract IERC20 {
64        function approve(address spender, uint256 amount) external returns (bool);
65        function allowance(address owner, address spender) external view returns (uint256);
66        function balanceOf(address account) external view returns (uint256);
67    }
68
69    /// TaskBond contract surface used by the auction-task operator bond flow
70    /// (`taskfast bond post`, gh#95). Only `post` is bound. The server verifies
71    /// the resulting `BondPosted` event by matching contract/token/`taskRef`/
72    /// amount — it does *not* pin `salt`, so any salt is accepted.
73    #[allow(missing_docs)]
74    contract TaskBond {
75        function post(
76            address token,
77            uint256 amount,
78            bytes32 taskRef,
79            bytes32 salt
80        ) external;
81    }
82}
83
84/// Private so no new public enum appears next to `TaskEscrowCalls`
85/// (cargo-semver-checks `enum_variant_added`); only the helper below is public.
86mod dispute_abi {
87    alloy_sol_types::sol! {
88        function dispute(bytes32 escrowId) external;
89    }
90}
91
92/// Calldata for `ArbitratedEscrow.dispute(escrowId)` (poster- or worker-signed
93/// dispute of a held escrow). The caller sends it from its own wallet.
94pub fn dispute_calldata(escrow_id: B256) -> Vec<u8> {
95    alloy_sol_types::SolCall::abi_encode(&dispute_abi::disputeCall {
96        escrowId: escrow_id,
97    })
98}
99
100/// Private for the same reason as `dispute_abi`. `state` is bound as `uint8`
101/// (ABI-identical to the contract's `EscrowState` enum) so no public enum appears.
102mod timeout_abi {
103    alloy_sol_types::sol! {
104        struct Escrow {
105            address poster;
106            address worker;
107            address platform;
108            address arbitrator;
109            address token;
110            uint256 deposit;
111            uint256 platformFeeAmount;
112            uint8 state;
113        }
114        function timeoutResolveDispute(bytes32 escrowId) external;
115        function getEscrow(bytes32 escrowId) external view returns (Escrow memory);
116        function disputedAt(bytes32 escrowId) external view returns (uint256);
117        function DISPUTE_TIMEOUT() external view returns (uint256);
118    }
119}
120
121/// `EscrowState::Disputed` in `ArbitratedEscrow.sol`.
122pub const ESCROW_STATE_DISPUTED: u8 = 5;
123
124/// Calldata for `ArbitratedEscrow.timeoutResolveDispute(escrowId)`. Anyone may
125/// send it once `disputedAt + DISPUTE_TIMEOUT` has passed on a `Disputed` escrow.
126pub fn timeout_resolve_calldata(escrow_id: B256) -> Vec<u8> {
127    alloy_sol_types::SolCall::abi_encode(&timeout_abi::timeoutResolveDisputeCall {
128        escrowId: escrow_id,
129    })
130}
131
132/// Calldata for the view `getEscrow(escrowId)`; decode with [`decode_escrow_state`].
133pub fn get_escrow_calldata(escrow_id: B256) -> Vec<u8> {
134    alloy_sol_types::SolCall::abi_encode(&timeout_abi::getEscrowCall {
135        escrowId: escrow_id,
136    })
137}
138
139/// Calldata for the view `disputedAt(escrowId)`; decode with [`decode_u256`].
140pub fn disputed_at_calldata(escrow_id: B256) -> Vec<u8> {
141    alloy_sol_types::SolCall::abi_encode(&timeout_abi::disputedAtCall {
142        escrowId: escrow_id,
143    })
144}
145
146/// Calldata for the view `DISPUTE_TIMEOUT()`; decode with [`decode_u256`].
147pub fn dispute_timeout_calldata() -> Vec<u8> {
148    alloy_sol_types::SolCall::abi_encode(&timeout_abi::DISPUTE_TIMEOUTCall {})
149}
150
151/// Decode a single `uint256` return (`disputedAt`, `DISPUTE_TIMEOUT`).
152pub fn decode_u256(data: &[u8]) -> Result<U256, String> {
153    <alloy_sol_types::sol_data::Uint<256> as alloy_sol_types::SolType>::abi_decode(data)
154        .map_err(|e| format!("not a uint256: {e}"))
155}
156
157/// Decode the raw `EscrowState` byte (0 None … 5 Disputed) out of a `getEscrow` return.
158pub fn decode_escrow_state(data: &[u8]) -> Result<u8, String> {
159    let e = <timeout_abi::Escrow as alloy_sol_types::SolType>::abi_decode(data)
160        .map_err(|e| format!("not an Escrow struct: {e}"))?;
161    Ok(e.state)
162}
163
164/// Derive the `bytes32 taskRef` that `TaskBond.post` binds for a given task.
165///
166/// The server verifier expects `taskRef` = 16 zero bytes concatenated with the
167/// task UUID's 16 raw bytes (gh#95). Kept next to [`compute_escrow_id`] because
168/// it is the same class of "must byte-match the on-chain/server derivation"
169/// helper: drift here silently posts a bond the verifier will never accept.
170pub fn compute_task_ref(task_id: uuid::Uuid) -> B256 {
171    let mut bytes = [0u8; 32];
172    bytes[16..].copy_from_slice(task_id.as_bytes());
173    B256::from(bytes)
174}
175
176/// Inputs to [`compute_escrow_id`] — one named field per preimage element.
177///
178/// Five fields are `Address` (`poster`, `worker`, `token`, `platform`,
179/// `arbitrator`). A positional argument list would let a caller silently
180/// transpose two of them and pre-sign a `DistributionApproval` against the
181/// wrong escrow id; named fields make the call site self-checking.
182pub struct EscrowIdParams {
183    /// Task poster funding the escrow.
184    pub poster: Address,
185    /// Worker who will be paid out.
186    pub worker: Address,
187    /// ERC-20 deposit token.
188    pub token: Address,
189    /// Deposit amount (pre fee-on-transfer; see module-level caveat).
190    pub deposit: U256,
191    /// Platform fee taken from the deposit.
192    pub platform_fee_amount: U256,
193    /// Platform wallet receiving the fee.
194    pub platform: Address,
195    /// Pool arbitrator bound to the escrow (v2; must be non-zero on-chain).
196    pub arbitrator: Address,
197    /// Random 32-byte salt.
198    pub salt: B256,
199}
200
201/// Predict the `escrowId` that `ArbitratedEscrow.open` will assign to a new escrow.
202///
203/// Computed as `keccak256(abi.encode(poster, worker, token, deposit, fee,
204/// platform, arbitrator, salt))` — must byte-match the contract's derivation in
205/// `ArbitratedEscrow.computeEscrowId` (`contracts/src/ArbitratedEscrow.sol`).
206/// The `arbitrator` is part of the preimage in canonical v2, so omitting it
207/// yields the wrong id (and a no-arbitrator `open` reverts on the v2 contract).
208/// Exposed so callers can pre-sign the EIP-712 `DistributionApproval` *before*
209/// broadcasting the `open` tx.
210pub fn compute_escrow_id(p: &EscrowIdParams) -> B256 {
211    let encoded = (
212        p.poster,
213        p.worker,
214        p.token,
215        p.deposit,
216        p.platform_fee_amount,
217        p.platform,
218        p.arbitrator,
219        p.salt,
220    )
221        .abi_encode();
222    keccak256(encoded)
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    /// Known-answer test pinning the `escrowId` preimage byte-layout.
230    ///
231    /// The expected digest is a frozen constant, NOT re-derived in-test — any
232    /// change to the field order / types / count inside [`compute_escrow_id`]
233    /// (e.g. moving `arbitrator`) flips it and fails CI. Regenerate ONLY from
234    /// the canonical contract/JS derivation (`ArbitratedEscrow.computeEscrowId`
235    /// / `assets/js/escrow_sign.js`) when the on-chain preimage intentionally
236    /// changes; pasting fresh Rust output back in would silently re-tautologize
237    /// the test and lose the cross-impl guarantee.
238    #[test]
239    fn compute_escrow_id_matches_known_vector() {
240        let mut salt_bytes = [0u8; 32];
241        salt_bytes[31] = 0x42;
242        let params = EscrowIdParams {
243            poster: "0x0000000000000000000000000000000000000001"
244                .parse()
245                .unwrap(),
246            worker: "0x0000000000000000000000000000000000000002"
247                .parse()
248                .unwrap(),
249            token: "0x0000000000000000000000000000000000000003"
250                .parse()
251                .unwrap(),
252            deposit: U256::from(1_000_000_000u64),
253            platform_fee_amount: U256::from(50_000_000u64),
254            platform: "0x0000000000000000000000000000000000000004"
255                .parse()
256                .unwrap(),
257            arbitrator: "0x0000000000000000000000000000000000000005"
258                .parse()
259                .unwrap(),
260            salt: B256::from(salt_bytes),
261        };
262
263        // Frozen digest for the 8-field preimage in canonical order
264        // (poster, worker, token, deposit, fee, platform, arbitrator, salt).
265        let expected: B256 = "0x1fada0b25ef1b0a435fd6b8ef78d4a068b13e77c95bb29635397ab0106835363"
266            .parse()
267            .expect("pinned escrow-id vector");
268        assert_eq!(compute_escrow_id(&params), expected);
269    }
270
271    #[test]
272    fn compute_escrow_id_is_salt_sensitive() {
273        let base = |salt: B256| EscrowIdParams {
274            poster: Address::ZERO,
275            worker: Address::ZERO,
276            token: Address::ZERO,
277            deposit: U256::from(1u64),
278            platform_fee_amount: U256::from(0u64),
279            platform: Address::ZERO,
280            arbitrator: Address::ZERO,
281            salt,
282        };
283
284        let mut salt_a = [0u8; 32];
285        salt_a[31] = 0x01;
286        let mut salt_b = [0u8; 32];
287        salt_b[31] = 0x02;
288
289        let a = compute_escrow_id(&base(B256::from(salt_a)));
290        let b = compute_escrow_id(&base(B256::from(salt_b)));
291        assert_ne!(a, b, "distinct salts must produce distinct escrow ids");
292    }
293
294    #[test]
295    fn approve_calldata_has_expected_selector() {
296        // ERC-20 `approve(address,uint256)` selector is 0x095ea7b3.
297        let call = IERC20::approveCall {
298            spender: Address::ZERO,
299            amount: U256::from(1u64),
300        };
301        let data = call.abi_encode();
302        assert_eq!(&data[0..4], &[0x09, 0x5e, 0xa7, 0xb3]);
303    }
304
305    #[test]
306    fn post_bond_calldata_has_expected_selector() {
307        // `TaskBond.post(address,uint256,bytes32,bytes32)` — the macro-derived
308        // selector must equal keccak(canonical signature)[..4]. Arg-order/type
309        // drift (e.g. swapping taskRef/salt or widening amount) fails this.
310        let call = TaskBond::postCall {
311            token: Address::ZERO,
312            amount: U256::from(1u64),
313            taskRef: B256::ZERO,
314            salt: B256::ZERO,
315        };
316        let data = call.abi_encode();
317        let expected = &keccak256("post(address,uint256,bytes32,bytes32)")[..4];
318        assert_eq!(&data[0..4], expected);
319    }
320
321    #[test]
322    fn compute_task_ref_left_pads_uuid_into_low_16_bytes() {
323        // 16 zero bytes ++ the task UUID's 16 raw bytes (gh#95 server verifier).
324        let id = uuid::Uuid::parse_str("00112233-4455-6677-8899-aabbccddeeff").unwrap();
325        let task_ref = compute_task_ref(id);
326        let bytes: [u8; 32] = task_ref.into();
327        assert_eq!(&bytes[..16], &[0u8; 16], "high 16 bytes must be zero");
328        assert_eq!(&bytes[16..], id.as_bytes(), "low 16 bytes must be the UUID");
329    }
330
331    #[test]
332    fn dispute_calldata_is_selector_plus_escrow_id() {
333        let id = B256::from([0xab; 32]);
334        let data = dispute_calldata(id);
335        // Second, independent derivation: keccak of the canonical signature.
336        assert_eq!(&data[..4], &keccak256("dispute(bytes32)")[..4]);
337        // Golden vector, computed offline: `cast calldata "dispute(bytes32)" 0xabab…ab`.
338        assert_eq!(
339            hex::encode(&data),
340            "add98c70abababababababababababababababababababababababababababababababab"
341        );
342    }
343
344    #[test]
345    fn timeout_resolve_abi_selectors_and_golden_calldata() {
346        let id = B256::from([0xab; 32]);
347        let tail = "abababababababababababababababababababababababababababababababab";
348        for (data, sig) in [
349            (
350                timeout_resolve_calldata(id),
351                "timeoutResolveDispute(bytes32)",
352            ),
353            (get_escrow_calldata(id), "getEscrow(bytes32)"),
354            (disputed_at_calldata(id), "disputedAt(bytes32)"),
355        ] {
356            assert_eq!(&data[..4], &keccak256(sig)[..4], "{sig}");
357            assert_eq!(hex::encode(&data[4..]), tail, "{sig}");
358        }
359        assert_eq!(
360            dispute_timeout_calldata(),
361            keccak256("DISPUTE_TIMEOUT()")[..4].to_vec()
362        );
363    }
364
365    #[test]
366    fn decoders_read_the_uint_and_the_state_word() {
367        let mut word = [0u8; 32];
368        word[31] = 7;
369        assert_eq!(decode_u256(&word).unwrap(), U256::from(7u64));
370        assert!(decode_u256(&word[..31]).is_err());
371        let mut escrow = [0u8; 256];
372        escrow[255] = ESCROW_STATE_DISPUTED;
373        assert_eq!(decode_escrow_state(&escrow).unwrap(), 5);
374        assert!(decode_escrow_state(&escrow[..224]).is_err());
375    }
376
377    #[test]
378    fn open_calldata_has_expected_selector() {
379        let call = TaskEscrow::openCall {
380            token: Address::ZERO,
381            deposit: U256::from(1u64),
382            worker: Address::ZERO,
383            platformFeeAmount: U256::from(0u64),
384            platform: Address::ZERO,
385            arbitrator: Address::ZERO,
386            salt: B256::ZERO,
387        };
388        let data = call.abi_encode();
389        // The `sol!`-generated selector must equal keccak(canonical signature)[..4].
390        // These are independent representations: `data[0..4]` is derived by the
391        // macro from the bound `open(...)` ABI above, while the string is the
392        // canonical Solidity signature. Arg-order / type drift on either side
393        // (e.g. dropping the new `address arbitrator`) fails this assert.
394        let expected =
395            &keccak256("open(address,uint256,address,uint256,address,address,bytes32)")[..4];
396        assert_eq!(&data[0..4], expected);
397    }
398}