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
70/// Inputs to [`compute_escrow_id`] — one named field per preimage element.
71///
72/// Five fields are `Address` (`poster`, `worker`, `token`, `platform`,
73/// `arbitrator`). A positional argument list would let a caller silently
74/// transpose two of them and pre-sign a `DistributionApproval` against the
75/// wrong escrow id; named fields make the call site self-checking.
76pub struct EscrowIdParams {
77    /// Task poster funding the escrow.
78    pub poster: Address,
79    /// Worker who will be paid out.
80    pub worker: Address,
81    /// ERC-20 deposit token.
82    pub token: Address,
83    /// Deposit amount (pre fee-on-transfer; see module-level caveat).
84    pub deposit: U256,
85    /// Platform fee taken from the deposit.
86    pub platform_fee_amount: U256,
87    /// Platform wallet receiving the fee.
88    pub platform: Address,
89    /// Pool arbitrator bound to the escrow (v2; must be non-zero on-chain).
90    pub arbitrator: Address,
91    /// Random 32-byte salt.
92    pub salt: B256,
93}
94
95/// Predict the `escrowId` that `ArbitratedEscrow.open` will assign to a new escrow.
96///
97/// Computed as `keccak256(abi.encode(poster, worker, token, deposit, fee,
98/// platform, arbitrator, salt))` — must byte-match the contract's derivation in
99/// `ArbitratedEscrow.computeEscrowId` (`contracts/src/ArbitratedEscrow.sol`).
100/// The `arbitrator` is part of the preimage in canonical v2, so omitting it
101/// yields the wrong id (and a no-arbitrator `open` reverts on the v2 contract).
102/// Exposed so callers can pre-sign the EIP-712 `DistributionApproval` *before*
103/// broadcasting the `open` tx.
104pub fn compute_escrow_id(p: &EscrowIdParams) -> B256 {
105    let encoded = (
106        p.poster,
107        p.worker,
108        p.token,
109        p.deposit,
110        p.platform_fee_amount,
111        p.platform,
112        p.arbitrator,
113        p.salt,
114    )
115        .abi_encode();
116    keccak256(encoded)
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    /// Known-answer test pinning the `escrowId` preimage byte-layout.
124    ///
125    /// The expected digest is a frozen constant, NOT re-derived in-test — any
126    /// change to the field order / types / count inside [`compute_escrow_id`]
127    /// (e.g. moving `arbitrator`) flips it and fails CI. Regenerate ONLY from
128    /// the canonical contract/JS derivation (`ArbitratedEscrow.computeEscrowId`
129    /// / `assets/js/escrow_sign.js`) when the on-chain preimage intentionally
130    /// changes; pasting fresh Rust output back in would silently re-tautologize
131    /// the test and lose the cross-impl guarantee.
132    #[test]
133    fn compute_escrow_id_matches_known_vector() {
134        let mut salt_bytes = [0u8; 32];
135        salt_bytes[31] = 0x42;
136        let params = EscrowIdParams {
137            poster: "0x0000000000000000000000000000000000000001"
138                .parse()
139                .unwrap(),
140            worker: "0x0000000000000000000000000000000000000002"
141                .parse()
142                .unwrap(),
143            token: "0x0000000000000000000000000000000000000003"
144                .parse()
145                .unwrap(),
146            deposit: U256::from(1_000_000_000u64),
147            platform_fee_amount: U256::from(50_000_000u64),
148            platform: "0x0000000000000000000000000000000000000004"
149                .parse()
150                .unwrap(),
151            arbitrator: "0x0000000000000000000000000000000000000005"
152                .parse()
153                .unwrap(),
154            salt: B256::from(salt_bytes),
155        };
156
157        // Frozen digest for the 8-field preimage in canonical order
158        // (poster, worker, token, deposit, fee, platform, arbitrator, salt).
159        let expected: B256 = "0x1fada0b25ef1b0a435fd6b8ef78d4a068b13e77c95bb29635397ab0106835363"
160            .parse()
161            .expect("pinned escrow-id vector");
162        assert_eq!(compute_escrow_id(&params), expected);
163    }
164
165    #[test]
166    fn compute_escrow_id_is_salt_sensitive() {
167        let base = |salt: B256| EscrowIdParams {
168            poster: Address::ZERO,
169            worker: Address::ZERO,
170            token: Address::ZERO,
171            deposit: U256::from(1u64),
172            platform_fee_amount: U256::from(0u64),
173            platform: Address::ZERO,
174            arbitrator: Address::ZERO,
175            salt,
176        };
177
178        let mut salt_a = [0u8; 32];
179        salt_a[31] = 0x01;
180        let mut salt_b = [0u8; 32];
181        salt_b[31] = 0x02;
182
183        let a = compute_escrow_id(&base(B256::from(salt_a)));
184        let b = compute_escrow_id(&base(B256::from(salt_b)));
185        assert_ne!(a, b, "distinct salts must produce distinct escrow ids");
186    }
187
188    #[test]
189    fn approve_calldata_has_expected_selector() {
190        // ERC-20 `approve(address,uint256)` selector is 0x095ea7b3.
191        let call = IERC20::approveCall {
192            spender: Address::ZERO,
193            amount: U256::from(1u64),
194        };
195        let data = call.abi_encode();
196        assert_eq!(&data[0..4], &[0x09, 0x5e, 0xa7, 0xb3]);
197    }
198
199    #[test]
200    fn open_calldata_has_expected_selector() {
201        let call = TaskEscrow::openCall {
202            token: Address::ZERO,
203            deposit: U256::from(1u64),
204            worker: Address::ZERO,
205            platformFeeAmount: U256::from(0u64),
206            platform: Address::ZERO,
207            arbitrator: Address::ZERO,
208            salt: B256::ZERO,
209        };
210        let data = call.abi_encode();
211        // The `sol!`-generated selector must equal keccak(canonical signature)[..4].
212        // These are independent representations: `data[0..4]` is derived by the
213        // macro from the bound `open(...)` ABI above, while the string is the
214        // canonical Solidity signature. Arg-order / type drift on either side
215        // (e.g. dropping the new `address arbitrator`) fails this assert.
216        let expected =
217            &keccak256("open(address,uint256,address,uint256,address,address,bytes32)")[..4];
218        assert_eq!(&data[0..4], expected);
219    }
220}