use std::path::PathBuf;
use alloy_primitives::Address;
use alloy_signer_local::PrivateKeySigner;
use serde_json::{json, Value};
use wiremock::matchers::{method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};
use taskfast_cli::cmd::escrow::{run, Command, SignArgs};
use taskfast_cli::cmd::{CmdError, Ctx};
use taskfast_cli::{Envelope, Environment};
const BID_ID: &str = "00000000-0000-0000-0000-0000000000bb";
const TASK_ID: &str = "00000000-0000-0000-0000-0000000000cc";
const TASK_ESCROW: &str = "0x0000000000000000000000000000000000000001";
const TOKEN_ADDR: &str = "0x0000000000000000000000000000000000000002";
const WORKER_ADDR: &str = "0x0000000000000000000000000000000000000003";
const PLATFORM_WALLET: &str = "0x0000000000000000000000000000000000000004";
const ARBITRATOR_ADDR: &str = "0x0000000000000000000000000000000000000005";
const CHAIN_ID: u64 = 42_431;
const POSTER_APPROVAL_DEADLINE: i64 = 4_102_444_800;
const POSTER_APPROVAL_MIN_LIFETIME: i64 = 10_368_000;
fn ctx_for(server: &MockServer, key: Option<&str>) -> Ctx {
Ctx {
api_key: key.map(String::from),
environment: Environment::Local,
api_base: Some(server.uri()),
config_path: std::path::PathBuf::from("/dev/null"),
dry_run: false,
quiet: true,
allow_custom_endpoints: true,
..Default::default()
}
}
fn envelope_value(env: &Envelope) -> Value {
serde_json::to_value(env).expect("serialize envelope")
}
struct Keys {
_tmp: tempfile::TempDir,
keystore_path: PathBuf,
password_path: PathBuf,
address: Address,
}
fn fresh_keys() -> Keys {
let signer = PrivateKeySigner::random();
let tmp = tempfile::tempdir().expect("tempdir");
let keystore_path = tmp.path().join("wallet.json");
taskfast_agent::keystore::save_signer(&signer, &keystore_path, "pw").expect("keystore");
let password_path = tmp.path().join("pw");
std::fs::write(&password_path, b"pw").expect("write password");
Keys {
address: signer.address(),
_tmp: tmp,
keystore_path,
password_path,
}
}
fn base_args(keys: &Keys) -> SignArgs {
SignArgs {
bid_id: BID_ID.into(),
keystore: Some(keys.keystore_path.display().to_string()),
wallet_password_file: Some(keys.password_path.clone()),
wallet_address: None,
rpc_url: Some("http://rpc.invalid".into()), skip_allowance_check: false,
receipt_timeout: None,
}
}
fn escrow_params_json() -> Value {
escrow_params_json_with_chain_id(CHAIN_ID)
}
fn escrow_params_json_with_chain_id(chain_id: u64) -> Value {
json!({
"bid_id": BID_ID,
"task_id": TASK_ID,
"amount": "75.00",
"platform_fee_amount": "3.75",
"worker_address": WORKER_ADDR,
"arbitrator_address": ARBITRATOR_ADDR,
"task_escrow_contract": TASK_ESCROW,
"token_address": TOKEN_ADDR,
"platform_wallet": PLATFORM_WALLET,
"chain_id": chain_id as i64,
"decimals": 6,
"memo_text": null,
"memo_hash": null,
"poster_approval_deadline": POSTER_APPROVAL_DEADLINE,
"poster_approval_min_lifetime": POSTER_APPROVAL_MIN_LIFETIME,
})
}
fn readiness_json() -> Value {
readiness_json_with_chain_id(CHAIN_ID)
}
fn readiness_json_with_chain_id(chain_id: u64) -> Value {
json!({
"ready_to_work": true,
"checks": {
"api_key": { "status": "complete" },
"wallet": { "status": "complete" },
"funded": { "status": "complete" },
"webhook": { "status": "complete" },
},
"settlement_domain": {
"chain_id": chain_id as i64,
"verifying_contract": TASK_ESCROW,
},
})
}
async fn mount_params(server: &MockServer, body: Value, status: u16) {
Mock::given(method("GET"))
.and(path(format!("/bids/{BID_ID}/escrow/params")))
.and(query_param("review_clock", "1"))
.respond_with(ResponseTemplate::new(status).set_body_json(body))
.mount(server)
.await;
}
async fn mount_readiness(server: &MockServer) {
Mock::given(method("GET"))
.and(path("/agents/me/readiness"))
.respond_with(ResponseTemplate::new(200).set_body_json(readiness_json()))
.mount(server)
.await;
}
async fn mount_readiness_with_chain_id(server: &MockServer, chain_id: u64) {
Mock::given(method("GET"))
.and(path("/agents/me/readiness"))
.respond_with(
ResponseTemplate::new(200).set_body_json(readiness_json_with_chain_id(chain_id)),
)
.mount(server)
.await;
}
#[tokio::test]
async fn escrow_sign_dry_run_signs_server_issued_deadline_verbatim() {
let server = MockServer::start().await;
let keys = fresh_keys();
mount_params(&server, escrow_params_json(), 200).await;
mount_readiness(&server).await;
let mut ctx = ctx_for(&server, Some("k"));
ctx.dry_run = true;
let env = run(&ctx, Command::Sign(base_args(&keys)))
.await
.expect("dry-run");
let deadline = envelope_value(&env)["data"]["deadline"]
.as_u64()
.expect("deadline");
assert_eq!(deadline, POSTER_APPROVAL_DEADLINE as u64);
}
#[tokio::test]
async fn escrow_sign_aborts_before_broadcast_when_deadline_below_min_lifetime() {
let server = MockServer::start().await;
let keys = fresh_keys();
let mut params = escrow_params_json();
params["poster_approval_deadline"] = json!(1_700_000_000i64); mount_params(&server, params, 200).await;
mount_readiness(&server).await;
let err = run(
&ctx_for(&server, Some("k")),
Command::Sign(base_args(&keys)),
)
.await
.expect_err("below-minimum deadline must abort");
match err {
CmdError::Validation { code, .. } => assert_eq!(code, "deadline_below_minimum"),
other => panic!("expected Validation(deadline_below_minimum), got {other:?}"),
}
}
#[tokio::test]
async fn escrow_sign_params_missing_deadline_is_actionable_version_skew() {
let server = MockServer::start().await;
let keys = fresh_keys();
let mut params = escrow_params_json();
params
.as_object_mut()
.unwrap()
.remove("poster_approval_deadline");
params
.as_object_mut()
.unwrap()
.remove("poster_approval_min_lifetime");
mount_params(&server, params, 200).await;
let err = run(
&ctx_for(&server, Some("k")),
Command::Sign(base_args(&keys)),
)
.await
.expect_err("missing deadline field must fail");
match err {
CmdError::Validation { code, .. } => assert_eq!(code, "server_missing_approval_deadline"),
other => panic!("expected Validation(server_missing_approval_deadline), got {other:?}"),
}
}
#[tokio::test]
async fn escrow_sign_dry_run_emits_signature_and_calldata_without_rpc() {
let server = MockServer::start().await;
let keys = fresh_keys();
mount_params(&server, escrow_params_json(), 200).await;
mount_readiness(&server).await;
let mut ctx = ctx_for(&server, Some("test-key"));
ctx.dry_run = true;
let envelope = run(&ctx, Command::Sign(base_args(&keys)))
.await
.expect("dry-run must succeed");
let v = envelope_value(&envelope);
assert_eq!(v["dry_run"], true);
assert_eq!(v["data"]["action"], "would_sign_escrow");
assert_eq!(v["data"]["bid_id"], BID_ID);
assert_eq!(v["data"]["task_id"], TASK_ID);
let sig = v["data"]["signature"].as_str().expect("signature");
assert_eq!(sig.len(), 132, "r||s||v hex is 0x + 65 bytes");
assert!(sig.starts_with("0x"));
let escrow_id = v["data"]["escrow_id"].as_str().expect("escrow_id");
assert_eq!(escrow_id.len(), 66, "bytes32 hex is 0x + 32 bytes");
let calldata = v["data"]["open_calldata"].as_str().expect("calldata");
assert!(
calldata.starts_with("0x") && calldata.len() >= 2 + 2 * (4 + 32 * 6),
"expected TaskEscrow.open calldata shape, got len={}",
calldata.len()
);
let _ = keys.address;
}
#[tokio::test]
async fn escrow_sign_rejects_custom_rpc_without_opt_in() {
let server = MockServer::start().await;
let keys = fresh_keys();
mount_params(&server, escrow_params_json(), 200).await;
mount_readiness(&server).await;
let mut ctx = ctx_for(&server, Some("test-key"));
ctx.allow_custom_endpoints = false;
ctx.dry_run = true;
let err = run(&ctx, Command::Sign(base_args(&keys)))
.await
.expect_err("custom rpc url must require opt-in");
match err {
CmdError::Usage(msg) => {
assert!(msg.contains("custom tempo_rpc_url"), "msg: {msg}");
assert!(msg.contains("--allow-custom-endpoints"), "msg: {msg}");
}
other => panic!("expected Usage, got {other:?}"),
}
}
#[tokio::test]
async fn escrow_sign_rejects_plain_http_mainnet_rpc() {
let server = MockServer::start().await;
let keys = fresh_keys();
mount_params(&server, escrow_params_json_with_chain_id(4_217), 200).await;
mount_readiness_with_chain_id(&server, 4_217).await;
let mut ctx = ctx_for(&server, Some("test-key"));
ctx.dry_run = true;
let err = run(&ctx, Command::Sign(base_args(&keys)))
.await
.expect_err("mainnet plain-http rpc must fail");
match err {
CmdError::Usage(msg) => {
assert!(msg.contains("plain-HTTP mainnet"), "msg: {msg}");
assert!(msg.contains("tempo_rpc_url"), "msg: {msg}");
}
other => panic!("expected Usage, got {other:?}"),
}
}
#[tokio::test]
async fn escrow_sign_params_403_maps_to_auth() {
let server = MockServer::start().await;
let keys = fresh_keys();
mount_params(
&server,
json!({ "error": "forbidden", "detail": "caller is not the poster" }),
403,
)
.await;
let err = run(
&ctx_for(&server, Some("test-key")),
Command::Sign(base_args(&keys)),
)
.await
.expect_err("403 must propagate");
assert!(matches!(err, CmdError::Auth(_)), "got {err:?}");
}
#[tokio::test]
async fn escrow_sign_params_409_wrong_status_maps_to_validation() {
let server = MockServer::start().await;
let keys = fresh_keys();
mount_params(
&server,
json!({ "error": "conflict", "detail": "bid not in :accepted_pending_escrow" }),
409,
)
.await;
let err = run(
&ctx_for(&server, Some("test-key")),
Command::Sign(base_args(&keys)),
)
.await
.expect_err("409 must propagate");
assert!(matches!(err, CmdError::Validation { .. }), "got {err:?}");
}
#[tokio::test]
async fn escrow_sign_zone_task_signs_against_params_domain_not_global_readiness() {
const ZONE_ESCROW: &str = "0x000000000000000000000000000000000000000a";
const ZONE_CHAIN_ID: u64 = 424_242;
let server = MockServer::start().await;
let keys = fresh_keys();
let mut params = escrow_params_json_with_chain_id(ZONE_CHAIN_ID);
params["task_escrow_contract"] = json!(ZONE_ESCROW);
mount_params(&server, params, 200).await;
mount_readiness(&server).await;
let mut ctx = ctx_for(&server, Some("test-key"));
ctx.dry_run = true;
let env = run(&ctx, Command::Sign(base_args(&keys)))
.await
.expect("zone task must sign against its own escrow domain");
let v = envelope_value(&env);
assert_eq!(v["data"]["domain"]["chain_id"], ZONE_CHAIN_ID);
assert_eq!(
v["data"]["domain"]["verifying_contract"]
.as_str()
.expect("verifying_contract")
.to_lowercase(),
ZONE_ESCROW,
);
}
#[tokio::test]
async fn escrow_sign_bad_uuid_is_usage_error_without_http() {
let server = MockServer::start().await;
let keys = fresh_keys();
let mut args = base_args(&keys);
args.bid_id = "not-a-uuid".into();
let err = run(&ctx_for(&server, Some("test-key")), Command::Sign(args))
.await
.expect_err("bad uuid must fail locally");
assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
}
#[tokio::test]
async fn escrow_sign_wallet_address_mismatch_aborts_before_rpc() {
let server = MockServer::start().await;
let keys = fresh_keys();
mount_params(&server, escrow_params_json(), 200).await;
mount_readiness(&server).await;
let mut args = base_args(&keys);
args.wallet_address = Some("0x0000000000000000000000000000000000000099".into());
let mut ctx = ctx_for(&server, Some("test-key"));
ctx.dry_run = true;
let err = run(&ctx, Command::Sign(args))
.await
.expect_err("wallet mismatch must fail");
match err {
CmdError::Usage(msg) => assert!(msg.contains("does not match"), "msg: {msg}"),
other => panic!("expected Usage, got {other:?}"),
}
}
const MEMO: &str = "0x1111111111111111111111111111111111111111111111111111111111111111";
fn selector_of(sig: &str) -> String {
format!(
"0x{}",
hex::encode(&alloy_primitives::keccak256(sig.as_bytes())[..4])
)
}
async fn dry_run_calldata(params: Value) -> Vec<u8> {
let server = MockServer::start().await;
let keys = fresh_keys();
mount_params(&server, params, 200).await;
mount_readiness(&server).await;
let mut ctx = ctx_for(&server, Some("k"));
ctx.dry_run = true;
let env = run(&ctx, Command::Sign(base_args(&keys)))
.await
.expect("dry-run");
let v = envelope_value(&env);
let hex_str = v["data"]["open_calldata"].as_str().expect("calldata");
hex::decode(hex_str.trim_start_matches("0x")).expect("hex")
}
fn word(calldata: &[u8], n: usize) -> &[u8] {
&calldata[4 + 32 * n..4 + 32 * (n + 1)]
}
fn u256_word(v: u64) -> [u8; 32] {
let mut w = [0u8; 32];
w[24..].copy_from_slice(&v.to_be_bytes());
w
}
const OPEN_SIG: &str = "open(address,uint256,address,uint256,address,address,bytes32)";
const MEMO_SIG: &str =
"openWithMemo(address,uint256,address,uint256,address,address,bytes32,bytes32)";
const REVIEW_SIG: &str =
"openWithReview(address,uint256,address,uint256,address,address,bytes32,uint256,bytes32)";
#[tokio::test]
async fn review_window_opens_with_review_and_zero_memo() {
let mut params = escrow_params_json();
params["review_window_seconds"] = json!(86_400);
let cd = dry_run_calldata(params).await;
assert_eq!(selector_of(REVIEW_SIG), "0xf1e32bb8");
assert_eq!(format!("0x{}", hex::encode(&cd[..4])), "0xf1e32bb8");
assert_eq!(cd.len(), 4 + 32 * 9);
assert_eq!(word(&cd, 7), u256_word(86_400));
assert_eq!(word(&cd, 8), [0u8; 32]);
}
#[tokio::test]
async fn review_window_with_memo_carries_memo_hash() {
let mut params = escrow_params_json();
params["review_window_seconds"] = json!(3_600);
params["memo_hash"] = json!(MEMO);
let cd = dry_run_calldata(params).await;
assert_eq!(
format!("0x{}", hex::encode(&cd[..4])),
selector_of(REVIEW_SIG)
);
assert_eq!(word(&cd, 7), u256_word(3_600));
assert_eq!(word(&cd, 8), [0x11u8; 32]);
}
#[tokio::test]
async fn absent_or_null_window_keeps_legacy_open() {
let cd = dry_run_calldata(escrow_params_json()).await;
assert_eq!(
format!("0x{}", hex::encode(&cd[..4])),
selector_of(OPEN_SIG)
);
assert_eq!(cd.len(), 4 + 32 * 7);
let mut null_window = escrow_params_json();
null_window["review_window_seconds"] = Value::Null;
let cd = dry_run_calldata(null_window).await;
assert_eq!(
format!("0x{}", hex::encode(&cd[..4])),
selector_of(OPEN_SIG)
);
let mut memo = escrow_params_json();
memo["memo_hash"] = json!(MEMO);
let cd = dry_run_calldata(memo).await;
assert_eq!(
format!("0x{}", hex::encode(&cd[..4])),
selector_of(MEMO_SIG)
);
assert_eq!(cd.len(), 4 + 32 * 8);
}
async fn sign_err(params: Value) -> CmdError {
let server = MockServer::start().await;
let keys = fresh_keys();
mount_params(&server, params, 200).await;
mount_readiness(&server).await;
run(
&ctx_for(&server, Some("k")),
Command::Sign(base_args(&keys)),
)
.await
.expect_err("bad window must abort")
}
#[tokio::test]
async fn bad_review_window_aborts_before_any_transaction() {
for bad in [json!(0), json!(-1), json!(9_007_199_254_740_993_i64)] {
let mut params = escrow_params_json();
params["review_window_seconds"] = bad.clone();
match sign_err(params).await {
CmdError::Validation { code, .. } => assert_eq!(code, "invalid_review_window", "{bad}"),
other => panic!("expected Validation(invalid_review_window) for {bad}, got {other:?}"),
}
}
}
#[tokio::test]
async fn malformed_review_window_says_no_transaction_was_sent() {
for bad in [json!(86_400.5), json!("86400"), json!(1.0e19)] {
let mut params = escrow_params_json();
params["review_window_seconds"] = bad.clone();
match sign_err(params).await {
CmdError::Decode(msg) => {
assert!(msg.contains("no transaction was sent"), "{bad}: msg: {msg}")
}
other => panic!("expected Decode for {bad}, got {other:?}"),
}
}
}
#[tokio::test]
async fn review_clock_required_409_surfaces_server_code() {
let server = MockServer::start().await;
let keys = fresh_keys();
mount_params(
&server,
json!({"error": "review_clock_client_required", "message": "Upgrade your CLI; send review_clock=1"}),
409,
)
.await;
let err = run(
&ctx_for(&server, Some("k")),
Command::Sign(base_args(&keys)),
)
.await
.expect_err("409");
match err {
CmdError::Validation { code, message } => {
assert_eq!(code, "review_clock_client_required");
assert!(message.contains("Upgrade your CLI"), "{message}");
}
other => panic!("expected Validation, got {other:?}"),
}
}
#[tokio::test]
async fn params_request_sends_review_clock_flag() {
let _ = dry_run_calldata(escrow_params_json()).await;
}