use serde_json::{Value, json};
use super::*;
use crate::{
error::VerificationKind,
testing::{
self, MAKER, NOW, OPERATOR, OTHER, OWNER, POOL, edited,
fixtures::{self, funded},
json::fixture,
},
};
fn check_with(
prepared: &Value,
request: &CapitalRequest,
existing: Option<&Order>,
) -> Result<Vec<Verified>, VerificationError> {
let authority = fixtures::authority(existing);
check_maker_intent(
&fixtures::maker(prepared),
request,
&authority,
EscrowEnvironment::Production,
fixtures::now(),
)
}
fn check(prepared: &Value) -> Result<Vec<Verified>, VerificationError> {
check_with(prepared, &fixtures::capital_request(FundingSource::Wallet), None)
}
fn fund(prepared: &mut Value) -> &mut Value {
&mut prepared["to_sign"][0]["typed_data"]["message"]
}
fn fund_domain(prepared: &mut Value) -> &mut Value {
&mut prepared["to_sign"][0]["typed_data"]["domain"]
}
const DEV_HL: &str = "0x948e65c40442d935d4ee990bdbd01bdd825c4873";
#[test]
fn a_funding_binds_only_the_requested_authority_domain_capital_and_request() {
let verified = check(&fixtures::maker_preparation()).unwrap();
assert_eq!(verified.len(), 1);
assert_eq!(verified[0].not_after(), Some(NOW + 3570));
let prepared = |edit: fn(&mut Value)| edited(fixtures::maker_preparation(), edit);
let item = fixtures::maker_preparation()["to_sign"][0].clone();
let max = U256::MAX.to_string();
let cases = [
(funded("operator", json!(OWNER)), details::FUND_OPERATOR),
(funded("quoteSigner", json!(OPERATOR)), details::FUND_QUOTE_SIGNER),
(funded("amount", json!("10000001")), details::FUND_AMOUNT),
(funded("deposit", json!("9999999")), details::FUND_DEPOSIT),
(funded("owner", json!(OTHER)), details::FUND_OWNER),
(funded("offerId", json!(testing::ORDER)), details::FUND_OFFER_ID),
(funded("minQuoteSequence", json!(0)), details::FUND_MIN_QUOTE_SEQUENCE),
(funded("minQuoteSequence", json!(1u64 << 53)), details::FUND_MIN_QUOTE_SEQUENCE),
(funded("deadline", json!((NOW + 7200).to_string())), details::DEADLINE),
(funded("deadline", json!(NOW.to_string())), details::DEADLINE),
(prepared(|p| fund_domain(p)["verifyingContract"] = json!(OWNER)), details::DOMAIN),
(prepared(|p| fund_domain(p)["chainId"] = json!(137)), details::DOMAIN),
(prepared(|p| fund_domain(p)["verifyingContract"] = json!(DEV_HL)), details::DOMAIN),
(
prepared(|p| {
p["to_sign"][0]["typed_data"]["types"]["FundOffer"][2]["type"] = json!("uint64");
}),
details::TYPES,
),
(prepared(|p| p["to_sign"][0]["signer"] = json!(OPERATOR)), details::FUND_SIGNER),
(prepared(|p| p["client_request_id"] = json!("another")), details::CLIENT_REQUEST_ID),
(
edited(fixtures::maker_preparation(), |p| p["to_sign"] = json!([item, item])),
details::TO_SIGN,
),
(prepared(|p| p["to_sign"] = json!([])), details::TO_SIGN),
(prepared(|p| p["state"] = json!("accepted")), details::STATE),
(prepared(|p| p["venue"] = json!("polymarket")), details::VENUE),
(prepared(|p| p["order"]["owner_address"] = json!(OTHER)), details::ORDER_OWNER_ADDRESS),
(prepared(|p| p["order"]["quote_signer"] = json!(OTHER)), details::ORDER_QUOTE_SIGNER),
(
prepared(|p| p["order"]["quote_identity_id"] = json!(testing::FILL)),
details::ORDER_QUOTE_IDENTITY_ID,
),
(prepared(|p| p["intent"]["amount"] = json!("1")), details::INTENT_AMOUNT),
(
prepared(|p| p["intent"]["quote_identity_id"] = json!(testing::FILL)),
details::INTENT_QUOTE_IDENTITY_ID,
),
(
prepared(|p| p["intent"]["funding_source"] = json!("venue")),
details::INTENT_FUNDING_SOURCE,
),
(prepared(|p| p["expected_revision"] = json!("2")), details::EXPECTED_REVISION),
(prepared(|p| p["expires_at"] = json!(testing::time(3631))), details::EXPIRES_AT),
(prepared(|p| p["order"]["last_sequence"] = json!(3)), details::ORDER),
(prepared(|p| p["sequence"] = json!(2)), details::SEQUENCE),
(prepared(|p| p["funding"]["venue_amount"] = json!("1")), details::FUNDING_IDLE_AMOUNT),
(
edited(fixtures::maker_preparation(), |p| {
p["funding"]["wallet_amount"] = json!(max);
p["funding"]["venue_amount"] = json!("1");
}),
details::FUNDING_DEPOSIT,
),
];
for (index, (prepared, detail)) in cases.iter().enumerate() {
assert_eq!(check(prepared).unwrap_err().detail, *detail, "case {index}");
}
let elsewhere = MakerAuthority { operator: OTHER, ..fixtures::authority(None) };
let error = check_maker_intent(
&fixtures::maker(&fixtures::maker_preparation()),
&fixtures::capital_request(FundingSource::Wallet),
&elsewhere,
EscrowEnvironment::Production,
fixtures::now(),
);
assert_eq!(error.unwrap_err().detail, details::FUND_OPERATOR);
}
#[test]
fn a_deposit_takes_the_available_balance_first() {
let idle = |patch: &Value, deposit: &str| {
edited(fixtures::maker_preparation(), |p| {
let mut funding = json!({"existing_available": "4000000", "idle_amount": "4000000", "wallet_amount": "6000000"});
fixtures::object(&mut funding).extend(patch.as_object().unwrap().clone());
fixtures::object(&mut p["funding"]).extend(funding.as_object().unwrap().clone());
fund(p)["deposit"] = json!(deposit);
})
};
assert!(check(&idle(&json!({}), "6000000")).is_ok());
let cases = [
(json!({"existing_available": "3000000"}), "6000000", details::FUNDING_DEPOSIT),
(
json!({"idle_amount": "0", "wallet_amount": "10000000"}),
"10000000",
details::FUNDING_DEPOSIT,
),
(
json!({"idle_amount": "3000000", "wallet_amount": "7000000"}),
"7000000",
details::FUNDING_DEPOSIT,
),
(
json!({"idle_amount": "4000000", "wallet_amount": "7000000"}),
"7000000",
details::FUNDING_IDLE_AMOUNT,
),
];
for (patch, deposit, detail) in cases {
assert_eq!(check(&idle(&patch, deposit)).unwrap_err().detail, detail, "{patch}");
}
}
#[test]
fn a_top_up_binds_the_pool_as_it_was_read() {
let live = |edit: fn(&mut Value)| -> Order {
let mut pool = fixtures::pool();
pool["state"] = json!("live");
pool["available_to_quote"] = json!("4000000");
edit(&mut pool);
fixtures::model(&pool)
};
let prepared = edited(fixtures::maker_preparation(), |p| {
p["order"]["available_to_quote"] = json!("4000000");
p["funding"]["existing_available"] = json!("4000000");
});
let request = fixtures::capital_request(FundingSource::Wallet);
let existing = live(|_| {});
assert!(check_with(&prepared, &request, Some(&existing)).is_ok());
assert_eq!(check(&prepared).unwrap_err().detail, details::ORDER);
let below = edited(prepared.clone(), |p| p["funding"]["existing_available"] = json!("3999999"));
assert_eq!(
check_with(&below, &request, Some(&existing)).unwrap_err().detail,
details::FUNDING_EXISTING_AVAILABLE
);
let moved = live(|pool| pool["available_to_quote"] = json!("5000000"));
let error = check_with(&prepared, &request, Some(&moved)).unwrap_err();
assert_eq!((error.kind, error.detail), (VerificationKind::Changed, details::MAKER_CAPITAL));
let newer = live(|pool| pool["revision"] = json!("2"));
assert_eq!(
check_with(&prepared, &request, Some(&newer)).unwrap_err().detail,
details::MAKER_CAPITAL
);
let other = live(|pool| pool["id"] = json!(testing::ORDER));
assert_eq!(
check_with(&prepared, &request, Some(&other)).unwrap_err().detail,
details::ORDER_ID
);
let foreign = live(|pool| pool["quote_signer"] = json!(OTHER));
assert_eq!(
check_with(&prepared, &request, Some(&foreign)).unwrap_err().detail,
details::EXISTING_ORDER
);
}
#[test]
fn venue_funding_moves_the_whole_deposit_out_of_margin_once() {
let request = fixtures::capital_request(FundingSource::Venue);
let verified = check_with(&fixtures::margin_preparation(), &request, None).unwrap();
assert_eq!(verified.len(), 2);
let served = eip712::parse::<crate::protocol::hyperliquid::SendAsset>(
&fixtures::margin_preparation()["to_sign"][0]["typed_data"],
)
.unwrap();
assert_eq!(verified[0].digest(), served.digest);
let cases = [
(
edited(fixtures::margin_preparation(), |p| {
p["to_sign"][0]["signer"] = json!(OTHER);
}),
details::MARGIN_MOVE_SIGNER,
),
(
edited(fixtures::margin_preparation(), |p| {
p["to_sign"][0]["typed_data"]["message"]["amount"] = json!("9");
}),
details::MARGIN_MOVE_AMOUNT,
),
(
edited(fixtures::margin_preparation(), |p| {
p["to_sign"][0]["typed_data"]["message"]["destination"] =
json!(format!("{OTHER:#x}"));
}),
details::DESTINATION,
),
(
edited(fixtures::margin_preparation(), |p| {
p["funding"]["wallet_amount"] = json!("1");
}),
details::FUNDING_IDLE_AMOUNT,
),
(
edited(fixtures::margin_preparation(), |p| {
let fund = p["to_sign"][1].clone();
p["to_sign"] = json!([fund]);
}),
details::TO_SIGN,
),
];
for (index, (prepared, detail)) in cases.iter().enumerate() {
assert_eq!(
check_with(prepared, &request, None).unwrap_err().detail,
*detail,
"case {index}"
);
}
let wallet_with_move = edited(fixtures::margin_preparation(), |p| {
p["intent"]["funding_source"] = json!("wallet");
});
let error =
check_with(&wallet_with_move, &fixtures::capital_request(FundingSource::Wallet), None);
assert_eq!(error.unwrap_err().detail, details::FUNDING_VENUE_AMOUNT);
let venue_from_wallet = edited(fixtures::maker_preparation(), |p| {
p["intent"]["funding_source"] = json!("venue");
});
assert_eq!(
check_with(&venue_from_wallet, &request, None).unwrap_err().detail,
details::FUNDING_WALLET_AMOUNT
);
}
#[test]
fn a_delegated_addition_signs_no_quote_set() {
let quote =
json!({"kind": "quote_set", "signer": MAKER, "typed_data": testing::sample("quote_set")});
let prepared = edited(fixtures::maker_preparation(), |p| {
p["to_sign"].as_array_mut().unwrap().push(quote);
p["sequence"] = json!(12);
});
assert_eq!(check(&prepared).unwrap_err().detail, details::TO_SIGN);
let lighter = CapitalRequest {
venue: VenueId::Lighter,
..fixtures::capital_request(FundingSource::Wallet)
};
assert_eq!(
check_with(&fixtures::maker_preparation(), &lighter, None).unwrap_err().kind,
VerificationKind::Unsupported
);
}
fn close(items: &Value, ids: &[&str]) -> Result<Verified, VerificationError> {
let ids: Vec<OrderId> = ids.iter().map(|id| id.parse().unwrap()).collect();
check_close_orders(
&fixtures::to_sign(items),
&ids,
OWNER,
EscrowEnvironment::Production,
fixtures::now(),
)
}
#[test]
fn a_close_names_only_asked_orders_of_the_master_within_the_hour() {
let both = [POOL, "0x5555555555555555555555555555555555555555555555555555555555555555"];
let verified = close(&fixtures::close_items(), &both).unwrap();
assert_eq!(verified.not_after(), Some(NOW + 3570));
let message = |name: &str, value: Value| {
edited(fixtures::close_items(), |items| {
items[0]["typed_data"]["message"][name] = value.clone();
})
};
let cases = [
(message("account", json!(OTHER)), details::ACCOUNT),
(message("orders", json!([])), details::ORDERS),
(message("orders", json!([POOL, POOL])), details::ORDERS),
(message("orders", json!([testing::ORDER])), details::ORDERS),
(message("deadline", json!((NOW + 3631).to_string())), details::DEADLINE),
(
edited(fixtures::close_items(), |items| items[0]["signer"] = json!(OTHER)),
details::TO_SIGN_SIGNER,
),
(edited(fixtures::close_items(), |items| items[0]["kind"] = json!("fund")), details::KIND),
(
edited(fixtures::close_items(), |items| {
items[0]["typed_data"]["domain"]["chainId"] = json!(137);
}),
details::DOMAIN,
),
];
for (index, (items, detail)) in cases.iter().enumerate() {
assert_eq!(close(items, &both).unwrap_err().detail, *detail, "case {index}");
}
assert_eq!(close(&fixtures::close_items(), &[POOL]).unwrap_err().detail, details::ORDERS);
let two = edited(fixtures::close_items(), |items| {
let item = items[0].clone();
items.as_array_mut().unwrap().push(item);
});
assert_eq!(close(&two, &both).unwrap_err().detail, details::TO_SIGN);
}
fn pool_order() -> Order {
let mut pool = fixtures::pool();
pool["last_sequence"] = json!(11);
fixtures::model(&pool)
}
fn quote_item() -> Value {
let mut typed = testing::sample("quote_set");
typed["message"]["owner"] = json!(OWNER);
json!({"kind": "quote_set", "signer": MAKER, "typed_data": typed})
}
fn quote_terms() -> Vec<QuoteTerms> {
["polymarket", "gmx"]
.into_iter()
.map(|venue| QuoteTerms {
venue: venue.parse().unwrap(),
recipient: OWNER,
supply: U256::from(500_000_000u64),
receive: U256::from(500_250_000u64),
min_fill: U256::from(10_000_000u64),
})
.collect()
}
fn signed_quote(item: &Value, requested: &[QuoteTerms]) -> Result<Verified, VerificationError> {
let item: ToSign = fixtures::model(item);
check_signed_quote(
&item,
&pool_order(),
requested,
12,
1_790_000_000,
1_790_003_601,
EscrowEnvironment::Production,
)
}
#[test]
fn a_quote_set_is_exactly_the_asked_quotes_in_order() {
assert!(signed_quote("e_item(), "e_terms()).is_ok());
let quote = |index: usize, name: &str, value: Value| {
edited(quote_item(), |item| {
item["typed_data"]["message"]["quotes"][index][name] = value.clone();
})
};
let cases = [
(quote(1, "venue", json!("polymarket")), details::QUOTES_VENUE),
(quote(1, "chainId", json!(137)), details::QUOTES_CHAIN_ID),
(quote(1, "token", json!(OTHER)), details::QUOTES_TOKEN),
(quote(1, "recipient", json!(OTHER)), details::QUOTES_RECIPIENT),
(quote(1, "supply", json!("500000001")), details::QUOTES_SUPPLY),
(quote(1, "receive", json!("1")), details::QUOTES_RECEIVE),
(quote(1, "minFill", json!("1")), details::QUOTES_MIN_FILL),
];
for (prepared, detail) in &cases {
let error = signed_quote(prepared, "e_terms()).unwrap_err();
assert_eq!((error.detail, error.index), (*detail, Some(1)));
}
let message = |name: &str, value: Value| {
edited(quote_item(), |item| item["typed_data"]["message"][name] = value.clone())
};
let cases = [
(message("owner", json!(OTHER)), details::OWNER),
(message("offerId", json!(testing::ORDER)), details::OFFER_ID),
(message("sequence", json!(13)), details::SEQUENCE),
(message("expiresAt", json!(1_790_003_602)), details::EXPIRES_AT),
(message("quotes", json!([])), details::QUOTES),
(edited(quote_item(), |item| item["signer"] = json!(OWNER)), details::TO_SIGN_SIGNER),
(edited(quote_item(), |item| item["kind"] = json!("fund")), details::KIND),
];
for (index, (prepared, detail)) in cases.iter().enumerate() {
assert_eq!(
signed_quote(prepared, "e_terms()).unwrap_err().detail,
*detail,
"case {index}"
);
}
let mut reversed = quote_terms();
reversed.reverse();
assert_eq!(signed_quote("e_item(), &reversed).unwrap_err().detail, details::QUOTES_VENUE);
assert_eq!(
signed_quote("e_item(), "e_terms()[..1]).unwrap_err().detail,
details::QUOTES
);
assert_eq!(signed_quote("e_item(), &[]).unwrap_err().detail, details::QUOTES);
let mut own = quote_terms();
own[0].venue = VenueId::Hyperliquid;
let own_item = quote(0, "venue", json!("hyperliquid"));
assert_eq!(signed_quote(&own_item, &own).unwrap_err().detail, details::QUOTES_VENUE);
let zero = quote_terms()
.into_iter()
.map(|terms| QuoteTerms { supply: U256::ZERO, min_fill: U256::ZERO, ..terms })
.collect::<Vec<_>>();
let zero_item = edited(quote_item(), |item| {
for quote in item["typed_data"]["message"]["quotes"].as_array_mut().unwrap() {
quote["supply"] = json!("0");
quote["minFill"] = json!("0");
}
});
assert_eq!(signed_quote(&zero_item, &zero).unwrap_err().detail, details::QUOTES_SUPPLY);
}
#[test]
fn a_created_credential_echoes_the_signer_and_scopes_asked() {
let created: CredentialCreated = serde_json::from_value(fixture("credential_created")).unwrap();
let scopes = created.scopes.clone();
assert!(check_created_credential(&created, created.quote_signer, &scopes).is_ok());
let error = check_created_credential(&created, OTHER, &scopes).unwrap_err();
assert_eq!(error.detail, details::CREDENTIAL_QUOTE_SIGNER);
let error = check_created_credential(&created, created.quote_signer, &scopes[1..]).unwrap_err();
assert_eq!(error.detail, details::CREDENTIAL_SCOPES);
}