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/// Derive the `bytes32 taskRef` that `TaskBond.post` binds for a given task.
85///
86/// The server verifier expects `taskRef` = 16 zero bytes concatenated with the
87/// task UUID's 16 raw bytes (gh#95). Kept next to [`compute_escrow_id`] because
88/// it is the same class of "must byte-match the on-chain/server derivation"
89/// helper: drift here silently posts a bond the verifier will never accept.
90pub fn compute_task_ref(task_id: uuid::Uuid) -> B256 {
91    let mut bytes = [0u8; 32];
92    bytes[16..].copy_from_slice(task_id.as_bytes());
93    B256::from(bytes)
94}
95
96/// Inputs to [`compute_escrow_id`] — one named field per preimage element.
97///
98/// Five fields are `Address` (`poster`, `worker`, `token`, `platform`,
99/// `arbitrator`). A positional argument list would let a caller silently
100/// transpose two of them and pre-sign a `DistributionApproval` against the
101/// wrong escrow id; named fields make the call site self-checking.
102pub struct EscrowIdParams {
103    /// Task poster funding the escrow.
104    pub poster: Address,
105    /// Worker who will be paid out.
106    pub worker: Address,
107    /// ERC-20 deposit token.
108    pub token: Address,
109    /// Deposit amount (pre fee-on-transfer; see module-level caveat).
110    pub deposit: U256,
111    /// Platform fee taken from the deposit.
112    pub platform_fee_amount: U256,
113    /// Platform wallet receiving the fee.
114    pub platform: Address,
115    /// Pool arbitrator bound to the escrow (v2; must be non-zero on-chain).
116    pub arbitrator: Address,
117    /// Random 32-byte salt.
118    pub salt: B256,
119}
120
121/// Predict the `escrowId` that `ArbitratedEscrow.open` will assign to a new escrow.
122///
123/// Computed as `keccak256(abi.encode(poster, worker, token, deposit, fee,
124/// platform, arbitrator, salt))` — must byte-match the contract's derivation in
125/// `ArbitratedEscrow.computeEscrowId` (`contracts/src/ArbitratedEscrow.sol`).
126/// The `arbitrator` is part of the preimage in canonical v2, so omitting it
127/// yields the wrong id (and a no-arbitrator `open` reverts on the v2 contract).
128/// Exposed so callers can pre-sign the EIP-712 `DistributionApproval` *before*
129/// broadcasting the `open` tx.
130pub fn compute_escrow_id(p: &EscrowIdParams) -> B256 {
131    let encoded = (
132        p.poster,
133        p.worker,
134        p.token,
135        p.deposit,
136        p.platform_fee_amount,
137        p.platform,
138        p.arbitrator,
139        p.salt,
140    )
141        .abi_encode();
142    keccak256(encoded)
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    /// Known-answer test pinning the `escrowId` preimage byte-layout.
150    ///
151    /// The expected digest is a frozen constant, NOT re-derived in-test — any
152    /// change to the field order / types / count inside [`compute_escrow_id`]
153    /// (e.g. moving `arbitrator`) flips it and fails CI. Regenerate ONLY from
154    /// the canonical contract/JS derivation (`ArbitratedEscrow.computeEscrowId`
155    /// / `assets/js/escrow_sign.js`) when the on-chain preimage intentionally
156    /// changes; pasting fresh Rust output back in would silently re-tautologize
157    /// the test and lose the cross-impl guarantee.
158    #[test]
159    fn compute_escrow_id_matches_known_vector() {
160        let mut salt_bytes = [0u8; 32];
161        salt_bytes[31] = 0x42;
162        let params = EscrowIdParams {
163            poster: "0x0000000000000000000000000000000000000001"
164                .parse()
165                .unwrap(),
166            worker: "0x0000000000000000000000000000000000000002"
167                .parse()
168                .unwrap(),
169            token: "0x0000000000000000000000000000000000000003"
170                .parse()
171                .unwrap(),
172            deposit: U256::from(1_000_000_000u64),
173            platform_fee_amount: U256::from(50_000_000u64),
174            platform: "0x0000000000000000000000000000000000000004"
175                .parse()
176                .unwrap(),
177            arbitrator: "0x0000000000000000000000000000000000000005"
178                .parse()
179                .unwrap(),
180            salt: B256::from(salt_bytes),
181        };
182
183        // Frozen digest for the 8-field preimage in canonical order
184        // (poster, worker, token, deposit, fee, platform, arbitrator, salt).
185        let expected: B256 = "0x1fada0b25ef1b0a435fd6b8ef78d4a068b13e77c95bb29635397ab0106835363"
186            .parse()
187            .expect("pinned escrow-id vector");
188        assert_eq!(compute_escrow_id(&params), expected);
189    }
190
191    #[test]
192    fn compute_escrow_id_is_salt_sensitive() {
193        let base = |salt: B256| EscrowIdParams {
194            poster: Address::ZERO,
195            worker: Address::ZERO,
196            token: Address::ZERO,
197            deposit: U256::from(1u64),
198            platform_fee_amount: U256::from(0u64),
199            platform: Address::ZERO,
200            arbitrator: Address::ZERO,
201            salt,
202        };
203
204        let mut salt_a = [0u8; 32];
205        salt_a[31] = 0x01;
206        let mut salt_b = [0u8; 32];
207        salt_b[31] = 0x02;
208
209        let a = compute_escrow_id(&base(B256::from(salt_a)));
210        let b = compute_escrow_id(&base(B256::from(salt_b)));
211        assert_ne!(a, b, "distinct salts must produce distinct escrow ids");
212    }
213
214    #[test]
215    fn approve_calldata_has_expected_selector() {
216        // ERC-20 `approve(address,uint256)` selector is 0x095ea7b3.
217        let call = IERC20::approveCall {
218            spender: Address::ZERO,
219            amount: U256::from(1u64),
220        };
221        let data = call.abi_encode();
222        assert_eq!(&data[0..4], &[0x09, 0x5e, 0xa7, 0xb3]);
223    }
224
225    #[test]
226    fn post_bond_calldata_has_expected_selector() {
227        // `TaskBond.post(address,uint256,bytes32,bytes32)` — the macro-derived
228        // selector must equal keccak(canonical signature)[..4]. Arg-order/type
229        // drift (e.g. swapping taskRef/salt or widening amount) fails this.
230        let call = TaskBond::postCall {
231            token: Address::ZERO,
232            amount: U256::from(1u64),
233            taskRef: B256::ZERO,
234            salt: B256::ZERO,
235        };
236        let data = call.abi_encode();
237        let expected = &keccak256("post(address,uint256,bytes32,bytes32)")[..4];
238        assert_eq!(&data[0..4], expected);
239    }
240
241    #[test]
242    fn compute_task_ref_left_pads_uuid_into_low_16_bytes() {
243        // 16 zero bytes ++ the task UUID's 16 raw bytes (gh#95 server verifier).
244        let id = uuid::Uuid::parse_str("00112233-4455-6677-8899-aabbccddeeff").unwrap();
245        let task_ref = compute_task_ref(id);
246        let bytes: [u8; 32] = task_ref.into();
247        assert_eq!(&bytes[..16], &[0u8; 16], "high 16 bytes must be zero");
248        assert_eq!(&bytes[16..], id.as_bytes(), "low 16 bytes must be the UUID");
249    }
250
251    #[test]
252    fn open_calldata_has_expected_selector() {
253        let call = TaskEscrow::openCall {
254            token: Address::ZERO,
255            deposit: U256::from(1u64),
256            worker: Address::ZERO,
257            platformFeeAmount: U256::from(0u64),
258            platform: Address::ZERO,
259            arbitrator: Address::ZERO,
260            salt: B256::ZERO,
261        };
262        let data = call.abi_encode();
263        // The `sol!`-generated selector must equal keccak(canonical signature)[..4].
264        // These are independent representations: `data[0..4]` is derived by the
265        // macro from the bound `open(...)` ABI above, while the string is the
266        // canonical Solidity signature. Arg-order / type drift on either side
267        // (e.g. dropping the new `address arbitrator`) fails this assert.
268        let expected =
269            &keccak256("open(address,uint256,address,uint256,address,address,bytes32)")[..4];
270        assert_eq!(&data[0..4], expected);
271    }
272}