diff --git a/precompiles/assets-erc20/src/eip2612.rs b/precompiles/assets-erc20/src/eip2612.rs index 4095586efc..29d98b5872 100644 --- a/precompiles/assets-erc20/src/eip2612.rs +++ b/precompiles/assets-erc20/src/eip2612.rs @@ -122,7 +122,7 @@ where Runtime::RuntimeCall: Dispatchable + GetDispatchInfo, Runtime::RuntimeCall: From>, ::RuntimeOrigin: From>, - BalanceOf: TryFrom + Into + EvmData, + BalanceOf: TryFrom + Into + solidity::Codec, Runtime: AccountIdAssetIdConversion>, <::RuntimeCall as Dispatchable>::RuntimeOrigin: OriginTrait, IsLocal: Get, @@ -145,13 +145,13 @@ where let version: H256 = keccak256!("1").into(); let chain_id: U256 = Runtime::ChainId::get().into(); - let domain_separator_inner = EvmDataWriter::new() - .write(H256::from(PERMIT_DOMAIN)) - .write(name) - .write(version) - .write(chain_id) - .write(Address(address)) - .build(); + let domain_separator_inner = solidity::encode_arguments(( + H256::from(PERMIT_DOMAIN), + name, + version, + chain_id, + Address(address), + )); keccak_256(&domain_separator_inner).into() } @@ -167,14 +167,14 @@ where ) -> [u8; 32] { let domain_separator = Self::compute_domain_separator(address, asset_id); - let permit_content = EvmDataWriter::new() - .write(H256::from(PERMIT_TYPEHASH)) - .write(Address(owner)) - .write(Address(spender)) - .write(value) - .write(nonce) - .write(deadline) - .build(); + let permit_content = solidity::encode_arguments(( + H256::from(PERMIT_TYPEHASH), + Address(owner), + Address(spender), + value, + nonce, + deadline, + )); let permit_content = keccak_256(&permit_content); let mut pre_digest = Vec::with_capacity(2 + 32 + 32); @@ -239,7 +239,7 @@ where SELECTOR_LOG_APPROVAL, owner, spender, - EvmDataWriter::new().write(value).build(), + solidity::encode_event_data(value), ) .record(handle)?; diff --git a/precompiles/assets-erc20/src/lib.rs b/precompiles/assets-erc20/src/lib.rs index 0066f30def..3834d9dccc 100644 --- a/precompiles/assets-erc20/src/lib.rs +++ b/precompiles/assets-erc20/src/lib.rs @@ -125,7 +125,7 @@ where Runtime::RuntimeCall: Dispatchable + GetDispatchInfo, Runtime::RuntimeCall: From>, ::RuntimeOrigin: From>, - BalanceOf: TryFrom + Into + EvmData, + BalanceOf: TryFrom + Into + solidity::Codec, Runtime: AccountIdAssetIdConversion>, <::RuntimeCall as Dispatchable>::RuntimeOrigin: OriginTrait, IsLocal: Get, @@ -226,7 +226,7 @@ where SELECTOR_LOG_APPROVAL, handle.context().caller, spender, - EvmDataWriter::new().write(value).build(), + solidity::encode_event_data(value), ) .record(handle)?; @@ -311,7 +311,7 @@ where SELECTOR_LOG_TRANSFER, handle.context().caller, to, - EvmDataWriter::new().write(value).build(), + solidity::encode_event_data(value), ) .record(handle)?; @@ -370,7 +370,7 @@ where SELECTOR_LOG_TRANSFER, from, to, - EvmDataWriter::new().write(value).build(), + solidity::encode_event_data(value), ) .record(handle)?; @@ -520,7 +520,7 @@ where SELECTOR_LOG_TRANSFER, H160::default(), to, - EvmDataWriter::new().write(value).build(), + solidity::encode_event_data(value), ) .record(handle)?; @@ -565,7 +565,7 @@ where SELECTOR_LOG_TRANSFER, from, H160::default(), - EvmDataWriter::new().write(value).build(), + solidity::encode_event_data(value), ) .record(handle)?; diff --git a/precompiles/assets-erc20/src/tests.rs b/precompiles/assets-erc20/src/tests.rs index 38e1371076..916b8a0276 100644 --- a/precompiles/assets-erc20/src/tests.rs +++ b/precompiles/assets-erc20/src/tests.rs @@ -172,7 +172,7 @@ fn get_total_supply() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(1000u64)); + .execute_returns(U256::from(1000u64)); }); } @@ -206,7 +206,7 @@ fn get_balances_known_user() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(1000u64)); + .execute_returns(U256::from(1000u64)); }); } @@ -234,7 +234,7 @@ fn get_balances_unknown_user() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u64)); + .execute_returns(U256::from(0u64)); }); } @@ -273,9 +273,9 @@ fn approve() { SELECTOR_LOG_APPROVAL, CryptoAlith, Bob, - EvmDataWriter::new().write(U256::from(500)).build(), + solidity::encode_event_data(U256::from(500)), )) - .execute_returns_encoded(true); + .execute_returns(true); }); } @@ -314,9 +314,9 @@ fn approve_saturating() { SELECTOR_LOG_APPROVAL, CryptoAlith, Bob, - EvmDataWriter::new().write(U256::MAX).build(), + solidity::encode_event_data(U256::MAX), )) - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test( @@ -329,7 +329,7 @@ fn approve_saturating() { ) .expect_cost(0u64) .expect_no_logs() - .execute_returns_encoded(U256::from(u128::MAX)); + .execute_returns(U256::from(u128::MAX)); }); } @@ -375,7 +375,7 @@ fn check_allowance_existing() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(500u64)); + .execute_returns(U256::from(500u64)); }); } @@ -404,7 +404,7 @@ fn check_allowance_not_existing() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u64)); + .execute_returns(U256::from(0u64)); }); } @@ -443,9 +443,9 @@ fn transfer() { SELECTOR_LOG_TRANSFER, CryptoAlith, Bob, - EvmDataWriter::new().write(U256::from(400)).build(), + solidity::encode_event_data(U256::from(400)), )) - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test( @@ -457,7 +457,7 @@ fn transfer() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(400)); + .execute_returns(U256::from(400)); precompiles() .prepare_test( @@ -469,7 +469,7 @@ fn transfer() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(600)); + .execute_returns(U256::from(600)); }); } @@ -570,9 +570,9 @@ fn transfer_from() { SELECTOR_LOG_TRANSFER, CryptoAlith, Charlie, - EvmDataWriter::new().write(U256::from(400)).build(), + solidity::encode_event_data(U256::from(400)), )) - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test( @@ -584,7 +584,7 @@ fn transfer_from() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(600)); + .execute_returns(U256::from(600)); precompiles() .prepare_test( @@ -596,7 +596,7 @@ fn transfer_from() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0)); + .execute_returns(U256::from(0)); precompiles() .prepare_test( @@ -608,7 +608,7 @@ fn transfer_from() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(400)); + .execute_returns(U256::from(400)); }); } @@ -648,9 +648,9 @@ fn transfer_from_non_incremental_approval() { SELECTOR_LOG_APPROVAL, CryptoAlith, Bob, - EvmDataWriter::new().write(U256::from(500)).build(), + solidity::encode_event_data(U256::from(500)), )) - .execute_returns_encoded(true); + .execute_returns(true); // We then approve 300. Non-incremental, so this is // the approved new value @@ -671,9 +671,9 @@ fn transfer_from_non_incremental_approval() { SELECTOR_LOG_APPROVAL, CryptoAlith, Bob, - EvmDataWriter::new().write(U256::from(300)).build(), + solidity::encode_event_data(U256::from(300)), )) - .execute_returns_encoded(true); + .execute_returns(true); // This should fail, as now the new approved quantity is 300 precompiles() @@ -779,9 +779,9 @@ fn transfer_from_self() { SELECTOR_LOG_TRANSFER, CryptoAlith, Bob, - EvmDataWriter::new().write(U256::from(400)).build(), + solidity::encode_event_data(U256::from(400)), )) - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test( @@ -793,7 +793,7 @@ fn transfer_from_self() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(600)); + .execute_returns(U256::from(600)); precompiles() .prepare_test( @@ -805,7 +805,7 @@ fn transfer_from_self() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(400)); + .execute_returns(U256::from(400)); }); } @@ -835,21 +835,13 @@ fn get_metadata() { .prepare_test(CryptoAlith, ForeignAssetId(0u128), ForeignPCall::name {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write::("TestToken".into()) - .build(), - ); + .execute_returns(UnboundedBytes::from("TestToken")); precompiles() .prepare_test(CryptoAlith, ForeignAssetId(0u128), ForeignPCall::symbol {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write::("Test".into()) - .build(), - ); + .execute_returns(UnboundedBytes::from("Test")); precompiles() .prepare_test( @@ -859,7 +851,7 @@ fn get_metadata() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(12u8); + .execute_returns(12u8); }); } @@ -946,9 +938,9 @@ fn mint_local_assets() { SELECTOR_LOG_TRANSFER, Zero, Bob, - EvmDataWriter::new().write(U256::from(400)).build(), + solidity::encode_event_data(U256::from(400)), )) - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test( @@ -960,7 +952,7 @@ fn mint_local_assets() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(400)); + .execute_returns(U256::from(400)); }); } @@ -1007,9 +999,9 @@ fn burn_local_assets() { SELECTOR_LOG_TRANSFER, CryptoAlith, Zero, - EvmDataWriter::new().write(U256::from(400)).build(), + solidity::encode_event_data(U256::from(400)), )) - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test( @@ -1021,7 +1013,7 @@ fn burn_local_assets() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(600)); + .execute_returns(U256::from(600)); }); } @@ -1063,7 +1055,7 @@ fn freeze_local_assets() { ) .expect_cost(17498000) // 1 weight => 1 gas in mock .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test( @@ -1121,7 +1113,7 @@ fn thaw_local_assets() { ) .expect_cost(17498000) // 1 weight => 1 gas in mock .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test( @@ -1133,7 +1125,7 @@ fn thaw_local_assets() { ) .expect_cost(17842000) // 1 weight => 1 gas in mock .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test( @@ -1150,9 +1142,9 @@ fn thaw_local_assets() { SELECTOR_LOG_TRANSFER, Bob, CryptoAlith, - EvmDataWriter::new().write(U256::from(400)).build(), + solidity::encode_event_data(U256::from(400)), )) - .execute_returns_encoded(true); + .execute_returns(true); }); } @@ -1192,7 +1184,7 @@ fn freeze_asset_local_asset() { ) .expect_cost(13719000) // 1 weight => 1 gas in mock .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test( @@ -1248,13 +1240,13 @@ fn thaw_asset_local_assets() { ) .expect_cost(13719000) // 1 weight => 1 gas in mock .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test(CryptoAlith, LocalAssetId(0u128), LocalPCall::thaw_asset {}) .expect_cost(13764000) // 1 weight => 1 gas in mock .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test( @@ -1271,9 +1263,9 @@ fn thaw_asset_local_assets() { SELECTOR_LOG_TRANSFER, Bob, CryptoAlith, - EvmDataWriter::new().write(U256::from(400)).build(), + solidity::encode_event_data(U256::from(400)), )) - .execute_returns_encoded(true); + .execute_returns(true); }); } @@ -1309,7 +1301,7 @@ fn transfer_ownership_local_assets() { ) .expect_cost(15366000) // 1 weight => 1 gas in mock .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); // Now Bob should be able to change ownership, and not CryptoAlith precompiles() @@ -1337,7 +1329,7 @@ fn transfer_ownership_local_assets() { ) .expect_cost(15366000) // 1 weight => 1 gas in mock .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); }); } @@ -1375,7 +1367,7 @@ fn set_team_local_assets() { ) .expect_cost(14437000) // 1 weight => 1 gas in mock .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); // Now Bob should be able to mint, and not CryptoAlith precompiles() @@ -1409,9 +1401,9 @@ fn set_team_local_assets() { SELECTOR_LOG_TRANSFER, Zero, Bob, - EvmDataWriter::new().write(U256::from(400)).build(), + solidity::encode_event_data(U256::from(400)), )) - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test( @@ -1423,7 +1415,7 @@ fn set_team_local_assets() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(400)); + .execute_returns(U256::from(400)); }); } @@ -1461,33 +1453,25 @@ fn set_metadata() { ) .expect_cost(24489304) // 1 weight => 1 gas in mock .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test(CryptoAlith, LocalAssetId(0u128), LocalPCall::name {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write::("TestToken".into()) - .build(), - ); + .execute_returns(UnboundedBytes::from("TestToken")); precompiles() .prepare_test(CryptoAlith, LocalAssetId(0u128), LocalPCall::symbol {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write::("Test".into()) - .build(), - ); + .execute_returns(UnboundedBytes::from("Test")); precompiles() .prepare_test(CryptoAlith, LocalAssetId(0u128), LocalPCall::decimals {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(12u8); + .execute_returns(12u8); }); } @@ -1525,7 +1509,7 @@ fn clear_metadata() { ) .expect_cost(24489304) // 1 weight => 1 gas in mock .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test( @@ -1535,33 +1519,25 @@ fn clear_metadata() { ) .expect_cost(24812000) // 1 weight => 1 gas in mock .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test(CryptoAlith, LocalAssetId(0u128), LocalPCall::name {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write::("".into()) - .build(), - ); + .execute_returns(UnboundedBytes::from("")); precompiles() .prepare_test(CryptoAlith, LocalAssetId(0u128), LocalPCall::symbol {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write::("".into()) - .build(), - ); + .execute_returns(UnboundedBytes::from("")); precompiles() .prepare_test(CryptoAlith, LocalAssetId(0u128), LocalPCall::decimals {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(0u8); + .execute_returns(0u8); }); } @@ -1614,7 +1590,7 @@ fn permit_valid() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); precompiles() .prepare_test( @@ -1636,9 +1612,9 @@ fn permit_valid() { SELECTOR_LOG_APPROVAL, CryptoAlith, Bob, - EvmDataWriter::new().write(U256::from(500)).build(), + solidity::encode_event_data(U256::from(500)), )) - .execute_returns(vec![]); + .execute_returns(()); precompiles() .prepare_test( @@ -1651,7 +1627,7 @@ fn permit_valid() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(500u16)); + .execute_returns(U256::from(500u16)); precompiles() .prepare_test( @@ -1663,7 +1639,7 @@ fn permit_valid() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(1u8)); + .execute_returns(U256::from(1u8)); }); } @@ -1723,7 +1699,7 @@ fn permit_valid_named_asset() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); precompiles() .prepare_test( @@ -1745,9 +1721,9 @@ fn permit_valid_named_asset() { SELECTOR_LOG_APPROVAL, CryptoAlith, Bob, - EvmDataWriter::new().write(U256::from(500)).build(), + solidity::encode_event_data(U256::from(500)), )) - .execute_returns(vec![]); + .execute_returns(()); precompiles() .prepare_test( @@ -1760,7 +1736,7 @@ fn permit_valid_named_asset() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(500u16)); + .execute_returns(U256::from(500u16)); precompiles() .prepare_test( @@ -1772,7 +1748,7 @@ fn permit_valid_named_asset() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(1u8)); + .execute_returns(U256::from(1u8)); }); } @@ -1825,7 +1801,7 @@ fn permit_invalid_nonce() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); precompiles() .prepare_test( @@ -1854,7 +1830,7 @@ fn permit_invalid_nonce() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u16)); + .execute_returns(U256::from(0u16)); precompiles() .prepare_test( @@ -1866,7 +1842,7 @@ fn permit_invalid_nonce() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); }); } @@ -1905,7 +1881,7 @@ fn permit_invalid_signature() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); precompiles() .prepare_test( @@ -1934,7 +1910,7 @@ fn permit_invalid_signature() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u16)); + .execute_returns(U256::from(0u16)); precompiles() .prepare_test( @@ -1946,7 +1922,7 @@ fn permit_invalid_signature() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); }); } @@ -2001,7 +1977,7 @@ fn permit_invalid_deadline() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); precompiles() .prepare_test( @@ -2030,7 +2006,7 @@ fn permit_invalid_deadline() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u16)); + .execute_returns(U256::from(0u16)); precompiles() .prepare_test( @@ -2042,7 +2018,7 @@ fn permit_invalid_deadline() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); }); } @@ -2223,9 +2199,9 @@ fn permit_valid_with_metamask_signed_data() { SELECTOR_LOG_APPROVAL, CryptoAlith, Bob, - EvmDataWriter::new().write(U256::from(1000)).build(), + solidity::encode_event_data(U256::from(1000)), )) - .execute_returns(vec![]); + .execute_returns(()); }); } @@ -2272,7 +2248,7 @@ fn transfer_amount_overflow() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0)); + .execute_returns(U256::from(0)); precompiles() .prepare_test( @@ -2284,7 +2260,7 @@ fn transfer_amount_overflow() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(1000)); + .execute_returns(U256::from(1000)); }); } @@ -2452,7 +2428,7 @@ fn get_owner() { .prepare_test(CryptoAlith, LocalAssetId(0u128), ForeignPCall::owner {}) .expect_cost(0) .expect_no_logs() - .execute_returns_encoded(Address(Bob.into())); + .execute_returns(Address(Bob.into())); }); } @@ -2485,7 +2461,7 @@ fn get_issuer() { .prepare_test(CryptoAlith, LocalAssetId(0u128), ForeignPCall::issuer {}) .expect_cost(0) .expect_no_logs() - .execute_returns_encoded(Address(Bob.into())); + .execute_returns(Address(Bob.into())); }); } @@ -2518,7 +2494,7 @@ fn get_admin() { .prepare_test(CryptoAlith, LocalAssetId(0u128), ForeignPCall::admin {}) .expect_cost(0) .expect_no_logs() - .execute_returns_encoded(Address(Bob.into())); + .execute_returns(Address(Bob.into())); }); } @@ -2551,33 +2527,16 @@ fn get_freezer() { .prepare_test(CryptoAlith, LocalAssetId(0u128), ForeignPCall::freezer {}) .expect_cost(0) .expect_no_logs() - .execute_returns_encoded(Address(Bob.into())); + .execute_returns(Address(Bob.into())); }); } #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { - for file in ["ERC20.sol", "LocalAsset.sol", "Permit.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !LocalPCall::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces( + &["ERC20.sol", "LocalAsset.sol", "Permit.sol"], + LocalPCall::supports_selector, + ) } #[test] @@ -2590,7 +2549,7 @@ fn test_deprecated_solidity_selectors_are_supported() { "set_metadata(string,string,uint8)", "clear_metadata()", ] { - let selector = solidity::compute_selector(deprecated_function); + let selector = compute_selector(deprecated_function); if !LocalPCall::supports_selector(selector) { panic!( "failed decoding selector 0x{:x} => '{}' as Action", diff --git a/precompiles/author-mapping/src/tests.rs b/precompiles/author-mapping/src/tests.rs index 293f837257..6c1e663ef0 100644 --- a/precompiles/author-mapping/src/tests.rs +++ b/precompiles/author-mapping/src/tests.rs @@ -325,10 +325,7 @@ fn set_keys_works() { // Create input with keys inside a Solidity bytes. let input = PCall::set_keys { - keys: EvmDataWriter::new() - .write(sp_core::H256::from([2u8; 32])) - .write(sp_core::H256::from([4u8; 32])) - .build() + keys: solidity::encode_arguments((H256::from([2u8; 32]), H256::from([4u8; 32]))) .into(), } .into(); @@ -393,7 +390,7 @@ mod nimbus_id_of { address: Address(address), }, ) - .execute_returns_encoded(expected); + .execute_returns(expected); }) } @@ -429,7 +426,7 @@ mod address_of { precompiles() .prepare_test(Bob, AuthorMappingAccount, PCall::address_of { nimbus_id }) - .execute_returns_encoded(Address(expected)); + .execute_returns(Address(expected)); }) } @@ -465,7 +462,7 @@ mod keys_of { precompiles() .prepare_test(Bob, AuthorMappingAccount, PCall::keys_of { nimbus_id }) - .execute_returns_encoded(expected); + .execute_returns(expected); }) } @@ -482,27 +479,10 @@ mod keys_of { #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { - for file in ["AuthorMappingInterface.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCall::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces( + &["AuthorMappingInterface.sol"], + PCall::supports_selector, + ) } #[test] @@ -514,7 +494,7 @@ fn test_deprecated_solidity_selectors_are_supported() { "remove_keys()", "set_keys(bytes)", ] { - let selector = solidity::compute_selector(deprecated_function); + let selector = compute_selector(deprecated_function); if !PCall::supports_selector(selector) { panic!( "failed decoding selector 0x{:x} => '{}' as Action", diff --git a/precompiles/balances-erc20/src/eip2612.rs b/precompiles/balances-erc20/src/eip2612.rs index 9d63abec1c..babb7747d6 100644 --- a/precompiles/balances-erc20/src/eip2612.rs +++ b/precompiles/balances-erc20/src/eip2612.rs @@ -45,18 +45,16 @@ where { pub fn compute_domain_separator(address: H160) -> [u8; 32] { let name: H256 = keccak_256(Metadata::name().as_bytes()).into(); - let version: H256 = keccak256!("1").into(); - let chain_id: U256 = Runtime::ChainId::get().into(); - let domain_separator_inner = EvmDataWriter::new() - .write(H256::from(PERMIT_DOMAIN)) - .write(name) - .write(version) - .write(chain_id) - .write(Address(address)) - .build(); + let domain_separator_inner = solidity::encode_arguments(( + H256::from(PERMIT_DOMAIN), + name, + version, + chain_id, + Address(address), + )); keccak_256(&domain_separator_inner).into() } @@ -71,14 +69,14 @@ where ) -> [u8; 32] { let domain_separator = Self::compute_domain_separator(address); - let permit_content = EvmDataWriter::new() - .write(H256::from(PERMIT_TYPEHASH)) - .write(Address(owner)) - .write(Address(spender)) - .write(value) - .write(nonce) - .write(deadline) - .build(); + let permit_content = solidity::encode_arguments(( + H256::from(PERMIT_TYPEHASH), + Address(owner), + Address(spender), + value, + nonce, + deadline, + )); let permit_content = keccak_256(&permit_content); let mut pre_digest = Vec::with_capacity(2 + 32 + 32); @@ -152,7 +150,7 @@ where SELECTOR_LOG_APPROVAL, owner, spender, - EvmDataWriter::new().write(value).build(), + solidity::encode_event_data(value), ) .record(handle)?; diff --git a/precompiles/balances-erc20/src/lib.rs b/precompiles/balances-erc20/src/lib.rs index f5351ed7af..7d04abbcc7 100644 --- a/precompiles/balances-erc20/src/lib.rs +++ b/precompiles/balances-erc20/src/lib.rs @@ -255,7 +255,7 @@ where SELECTOR_LOG_APPROVAL, handle.context().caller, spender, - EvmDataWriter::new().write(value).build(), + solidity::encode_event_data(value), ) .record(handle)?; @@ -291,7 +291,7 @@ where SELECTOR_LOG_TRANSFER, handle.context().caller, to, - EvmDataWriter::new().write(value).build(), + solidity::encode_event_data(value), ) .record(handle)?; @@ -354,7 +354,7 @@ where SELECTOR_LOG_TRANSFER, from, to, - EvmDataWriter::new().write(value).build(), + solidity::encode_event_data(value), ) .record(handle)?; @@ -413,9 +413,7 @@ where handle.context().address, SELECTOR_LOG_DEPOSIT, handle.context().caller, - EvmDataWriter::new() - .write(handle.context().apparent_value) - .build(), + solidity::encode_event_data(handle.context().apparent_value), ) .record(handle)?; @@ -445,7 +443,7 @@ where handle.context().address, SELECTOR_LOG_WITHDRAWAL, handle.context().caller, - EvmDataWriter::new().write(value).build(), + solidity::encode_event_data(value), ) .record(handle)?; diff --git a/precompiles/balances-erc20/src/tests.rs b/precompiles/balances-erc20/src/tests.rs index 602791dc24..54ae95fcd5 100644 --- a/precompiles/balances-erc20/src/tests.rs +++ b/precompiles/balances-erc20/src/tests.rs @@ -101,7 +101,7 @@ fn get_total_supply() { .prepare_test(CryptoAlith, Precompile1, PCall::total_supply {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(3500u64)); + .execute_returns(U256::from(3500u64)); }); } @@ -121,7 +121,7 @@ fn get_balances_known_user() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(1000u64)); + .execute_returns(U256::from(1000u64)); }); } @@ -141,7 +141,7 @@ fn get_balances_unknown_user() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u64)); + .execute_returns(U256::from(0u64)); }); } @@ -166,9 +166,9 @@ fn approve() { SELECTOR_LOG_APPROVAL, CryptoAlith, Bob, - EvmDataWriter::new().write(U256::from(500)).build(), + solidity::encode_event_data(U256::from(500)), )) - .execute_returns_encoded(true); + .execute_returns(true); }); } @@ -193,9 +193,9 @@ fn approve_saturating() { SELECTOR_LOG_APPROVAL, CryptoAlith, Bob, - EvmDataWriter::new().write(U256::MAX).build(), + solidity::encode_event_data(U256::MAX), )) - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test( @@ -208,7 +208,7 @@ fn approve_saturating() { ) .expect_cost(0) .expect_no_logs() - .execute_returns_encoded(U256::from(u128::MAX)); + .execute_returns(U256::from(u128::MAX)); }); } @@ -240,7 +240,7 @@ fn check_allowance_existing() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(500u64)); + .execute_returns(U256::from(500u64)); }); } @@ -261,7 +261,7 @@ fn check_allowance_not_existing() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u64)); + .execute_returns(U256::from(0u64)); }); } @@ -286,9 +286,9 @@ fn transfer() { SELECTOR_LOG_TRANSFER, CryptoAlith, Bob, - EvmDataWriter::new().write(U256::from(400)).build(), + solidity::encode_event_data(U256::from(400)), )) - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test( @@ -300,7 +300,7 @@ fn transfer() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(600)); + .execute_returns(U256::from(600)); precompiles() .prepare_test( @@ -312,7 +312,7 @@ fn transfer() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(400)); + .execute_returns(U256::from(400)); }); } @@ -373,9 +373,9 @@ fn transfer_from() { SELECTOR_LOG_TRANSFER, CryptoAlith, Bob, - EvmDataWriter::new().write(U256::from(400)).build(), + solidity::encode_event_data(U256::from(400)), )) - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test( @@ -387,7 +387,7 @@ fn transfer_from() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(600)); + .execute_returns(U256::from(600)); precompiles() .prepare_test( @@ -399,7 +399,7 @@ fn transfer_from() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(400)); + .execute_returns(U256::from(400)); precompiles() .prepare_test( @@ -412,7 +412,7 @@ fn transfer_from() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(100u64)); + .execute_returns(U256::from(100u64)); }); } @@ -469,9 +469,9 @@ fn transfer_from_self() { SELECTOR_LOG_TRANSFER, CryptoAlith, Bob, - EvmDataWriter::new().write(U256::from(400)).build(), + solidity::encode_event_data(U256::from(400)), )) - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test( @@ -483,7 +483,7 @@ fn transfer_from_self() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(600)); + .execute_returns(U256::from(600)); precompiles() .prepare_test( @@ -495,7 +495,7 @@ fn transfer_from_self() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(400)); + .execute_returns(U256::from(400)); }); } @@ -509,11 +509,7 @@ fn get_metadata_name() { .prepare_test(CryptoAlith, Precompile1, PCall::name {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write::("Mock token".into()) - .build(), - ); + .execute_returns(UnboundedBytes::from("Mock token")); }); } @@ -527,11 +523,7 @@ fn get_metadata_symbol() { .prepare_test(CryptoAlith, Precompile1, PCall::symbol {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write::("MOCK".into()) - .build(), - ); + .execute_returns(UnboundedBytes::from("MOCK")); }); } @@ -545,7 +537,7 @@ fn get_metadata_decimals() { .prepare_test(CryptoAlith, Precompile1, PCall::decimals {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(18u8); + .execute_returns(18u8); }); } @@ -565,7 +557,7 @@ fn deposit(data: Vec) { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0)); + .execute_returns(U256::from(0)); // Deposit // We need to call using EVM pallet so we can check the EVM correctly sends the amount @@ -612,7 +604,7 @@ fn deposit(data: Vec) { Precompile1, SELECTOR_LOG_DEPOSIT, CryptoAlith, - EvmDataWriter::new().write(U256::from(500)).build(), + solidity::encode_event_data(U256::from(500)), ) }), RuntimeEvent::Evm(pallet_evm::Event::Executed { @@ -632,7 +624,7 @@ fn deposit(data: Vec) { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0)); + .execute_returns(U256::from(0)); // Check CryptoAlith balance is still 1000. precompiles() @@ -645,7 +637,7 @@ fn deposit(data: Vec) { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(1000)); + .execute_returns(U256::from(1000)); }); } @@ -656,7 +648,7 @@ fn deposit_function() { #[test] fn deposit_fallback() { - deposit(EvmDataWriter::new_with_selector(0x01234567u32).build()) + deposit(solidity::encode_with_selector(0x01234567u32, ())) } #[test] @@ -681,7 +673,7 @@ fn deposit_zero() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0)); + .execute_returns(U256::from(0)); // Deposit // We need to call using EVM pallet so we can check the EVM correctly sends the amount @@ -718,7 +710,7 @@ fn deposit_zero() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0)); + .execute_returns(U256::from(0)); // Check CryptoAlith balance is still 1000. precompiles() @@ -731,7 +723,7 @@ fn deposit_zero() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(1000)); + .execute_returns(U256::from(1000)); }); } @@ -752,7 +744,7 @@ fn withdraw() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0)); + .execute_returns(U256::from(0)); // Withdraw precompiles() @@ -766,9 +758,9 @@ fn withdraw() { Precompile1, SELECTOR_LOG_WITHDRAWAL, CryptoAlith, - EvmDataWriter::new().write(U256::from(500)).build(), + solidity::encode_event_data(U256::from(500)), )) - .execute_returns(vec![]); + .execute_returns(()); // Check CryptoAlith balance is still 1000. precompiles() @@ -781,7 +773,7 @@ fn withdraw() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(1000)); + .execute_returns(U256::from(1000)); }); } @@ -802,7 +794,7 @@ fn withdraw_more_than_owned() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0)); + .execute_returns(U256::from(0)); // Withdraw precompiles() @@ -824,7 +816,7 @@ fn withdraw_more_than_owned() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(1000)); + .execute_returns(U256::from(1000)); }); } @@ -862,7 +854,7 @@ fn permit_valid() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); precompiles() .prepare_test( @@ -884,9 +876,9 @@ fn permit_valid() { SELECTOR_LOG_APPROVAL, CryptoAlith, Bob, - EvmDataWriter::new().write(U256::from(value)).build(), + solidity::encode_event_data(U256::from(value)), )) - .execute_returns(vec![]); + .execute_returns(()); precompiles() .prepare_test( @@ -899,7 +891,7 @@ fn permit_valid() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(500u16)); + .execute_returns(U256::from(500u16)); precompiles() .prepare_test( @@ -911,7 +903,7 @@ fn permit_valid() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(1u8)); + .execute_returns(U256::from(1u8)); }); } @@ -949,7 +941,7 @@ fn permit_invalid_nonce() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); precompiles() .prepare_test( @@ -978,7 +970,7 @@ fn permit_invalid_nonce() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u16)); + .execute_returns(U256::from(0u16)); precompiles() .prepare_test( @@ -990,7 +982,7 @@ fn permit_invalid_nonce() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); }); } @@ -1015,7 +1007,7 @@ fn permit_invalid_signature() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); precompiles() .prepare_test( @@ -1044,7 +1036,7 @@ fn permit_invalid_signature() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u16)); + .execute_returns(U256::from(0u16)); precompiles() .prepare_test( @@ -1056,7 +1048,7 @@ fn permit_invalid_signature() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); }); } @@ -1096,7 +1088,7 @@ fn permit_invalid_deadline() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); precompiles() .prepare_test( @@ -1125,7 +1117,7 @@ fn permit_invalid_deadline() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u16)); + .execute_returns(U256::from(0u16)); precompiles() .prepare_test( @@ -1137,7 +1129,7 @@ fn permit_invalid_deadline() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); }); } @@ -1303,33 +1295,16 @@ fn permit_valid_with_metamask_signed_data() { SELECTOR_LOG_APPROVAL, CryptoAlith, Bob, - EvmDataWriter::new().write(U256::from(1000)).build(), + solidity::encode_event_data(U256::from(1000)), )) - .execute_returns(vec![]); + .execute_returns(()); }); } #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { - for file in ["ERC20.sol", "Permit.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCall::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces( + &["ERC20.sol", "Permit.sol"], + PCall::supports_selector, + ) } diff --git a/precompiles/batch/src/lib.rs b/precompiles/batch/src/lib.rs index 3083349a8d..8453275379 100644 --- a/precompiles/batch/src/lib.rs +++ b/precompiles/batch/src/lib.rs @@ -21,7 +21,7 @@ use evm::{ExitError, ExitReason}; use fp_evm::{Context, Log, PrecompileFailure, PrecompileHandle, Transfer}; use frame_support::traits::ConstU32; -use precompile_utils::{costs::call_cost, prelude::*}; +use precompile_utils::{evm::costs::call_cost, prelude::*}; use sp_core::{H160, U256}; use sp_std::{iter::repeat, marker::PhantomData, vec, vec::Vec}; @@ -49,7 +49,7 @@ pub fn log_subcall_succeeded(address: impl Into, index: usize) -> Log { log1( address, LOG_SUBCALL_SUCCEEDED, - EvmDataWriter::new().write(U256::from(index)).build(), + solidity::encode_event_data(U256::from(index)), ) } @@ -57,7 +57,7 @@ pub fn log_subcall_failed(address: impl Into, index: usize) -> Log { log1( address, LOG_SUBCALL_FAILED, - EvmDataWriter::new().write(U256::from(index)).build(), + solidity::encode_event_data(U256::from(index)), ) } diff --git a/precompiles/batch/src/tests.rs b/precompiles/batch/src/tests.rs index b88d599c79..6617f13154 100644 --- a/precompiles/batch/src/tests.rs +++ b/precompiles/batch/src/tests.rs @@ -21,14 +21,14 @@ use crate::mock::{ use crate::{ log_subcall_failed, log_subcall_succeeded, Mode, LOG_SUBCALL_FAILED, LOG_SUBCALL_SUCCEEDED, }; -use evm::ExitReason; -use fp_evm::{ExitError, ExitRevert, ExitSucceed}; +use fp_evm::ExitError; use frame_support::{ assert_ok, dispatch::{DispatchError, Dispatchable}, }; use pallet_evm::Call as EvmCall; -use precompile_utils::{costs::call_cost, prelude::*, revert::RevertSelector, testing::*}; +use precompile_utils::solidity::revert::revert_as_bytes; +use precompile_utils::{evm::costs::call_cost, prelude::*, testing::*}; use sp_core::{H160, H256, U256}; use sp_runtime::{DispatchErrorWithPostInfo, ModuleError}; @@ -101,7 +101,7 @@ fn batch_some_empty() { }, ) .with_subcall_handle(|Subcall { .. }| panic!("there should be no subcall")) - .execute_returns(Vec::new()) + .execute_returns(()) }) } @@ -120,7 +120,7 @@ fn batch_some_until_failure_empty() { }, ) .with_subcall_handle(|Subcall { .. }| panic!("there should be no subcall")) - .execute_returns(Vec::new()) + .execute_returns(()) }) } @@ -139,7 +139,7 @@ fn batch_all_empty() { }, ) .with_subcall_handle(|Subcall { .. }| panic!("there should be no subcall")) - .execute_returns(Vec::new()) + .execute_returns(()) }) } @@ -199,10 +199,9 @@ fn batch_returns( assert_eq!(&input, b"one"); SubcallOutput { - reason: ExitReason::Succeed(ExitSucceed::Returned), - output: Vec::new(), cost: 13, logs: vec![log1(Bob, H256::repeat_byte(0x11), vec![])], + ..SubcallOutput::succeed() } } a if a == Charlie.into() => { @@ -225,10 +224,9 @@ fn batch_returns( assert_eq!(&input, b"two"); SubcallOutput { - reason: ExitReason::Succeed(ExitSucceed::Returned), - output: Vec::new(), cost: 17, logs: vec![log1(Charlie, H256::repeat_byte(0x22), vec![])], + ..SubcallOutput::succeed() } } _ => panic!("unexpected subcall"), @@ -245,7 +243,7 @@ fn batch_some_returns() { .expect_log(log_subcall_succeeded(Batch, 0)) .expect_log(log1(Charlie, H256::repeat_byte(0x22), vec![])) .expect_log(log_subcall_succeeded(Batch, 1)) - .execute_returns(Vec::new()) + .execute_returns(()) }) } @@ -257,7 +255,7 @@ fn batch_some_until_failure_returns() { .expect_log(log_subcall_succeeded(Batch, 0)) .expect_log(log1(Charlie, H256::repeat_byte(0x22), vec![])) .expect_log(log_subcall_succeeded(Batch, 1)) - .execute_returns(Vec::new()) + .execute_returns(()) }) } @@ -269,7 +267,7 @@ fn batch_all_returns() { .expect_log(log_subcall_succeeded(Batch, 0)) .expect_log(log1(Charlie, H256::repeat_byte(0x22), vec![])) .expect_log(log_subcall_succeeded(Batch, 1)) - .execute_returns(Vec::new()) + .execute_returns(()) }) } @@ -324,10 +322,8 @@ fn batch_out_of_gas( assert_eq!(&input, b"one"); SubcallOutput { - reason: ExitReason::Error(ExitError::OutOfGas), - output: Vec::new(), cost: 11_000, - logs: vec![], + ..SubcallOutput::out_of_gas() } } _ => panic!("unexpected subcall"), @@ -340,7 +336,7 @@ fn batch_some_out_of_gas() { ExtBuilder::default().build().execute_with(|| { batch_out_of_gas(&precompiles(), Mode::BatchSome) .expect_log(log_subcall_failed(Batch, 0)) - .execute_returns(Vec::new()) + .execute_returns(()) }) } @@ -349,7 +345,7 @@ fn batch_some_until_failure_out_of_gas() { ExtBuilder::default().build().execute_with(|| { batch_out_of_gas(&precompiles(), Mode::BatchSomeUntilFailure) .expect_log(log_subcall_failed(Batch, 0)) - .execute_returns(Vec::new()) + .execute_returns(()) }) } @@ -420,10 +416,9 @@ fn batch_incomplete( assert_eq!(&input, b"one"); SubcallOutput { - reason: ExitReason::Succeed(ExitSucceed::Returned), - output: Vec::new(), cost: 13, logs: vec![log1(Bob, H256::repeat_byte(0x11), vec![])], + ..SubcallOutput::succeed() } } a if a == Charlie.into() => { @@ -446,12 +441,9 @@ fn batch_incomplete( assert_eq!(&input, b""); SubcallOutput { - reason: ExitReason::Revert(ExitRevert::Reverted), - output: EvmDataWriter::new_with_selector(RevertSelector::Generic) - .write::(b"Revert message".into()) - .build(), + output: revert_as_bytes("Revert message"), cost: 17, - logs: vec![], + ..SubcallOutput::revert() } } a if a == Alice.into() => { @@ -474,10 +466,9 @@ fn batch_incomplete( assert_eq!(&input, b""); SubcallOutput { - reason: ExitReason::Succeed(ExitSucceed::Returned), - output: Vec::new(), cost: 19, logs: vec![log1(Alice, H256::repeat_byte(0x33), vec![])], + ..SubcallOutput::succeed() } } _ => panic!("unexpected subcall"), @@ -497,7 +488,7 @@ fn batch_some_incomplete() { .expect_log(log1(Alice, H256::repeat_byte(0x33), vec![])) .expect_log(log_subcall_succeeded(Batch, 2)) .expect_cost(13 + 17 + 19 + total_call_cost * 3) - .execute_returns(Vec::new()) + .execute_returns(()) }) } @@ -511,7 +502,7 @@ fn batch_some_until_failure_incomplete() { .expect_log(log_subcall_succeeded(Batch, 0)) .expect_log(log_subcall_failed(Batch, 1)) .expect_cost(13 + 17 + total_call_cost * 2) - .execute_returns(Vec::new()) + .execute_returns(()) }) } @@ -557,7 +548,7 @@ fn batch_some_log_out_of_gas() { ExtBuilder::default().build().execute_with(|| { batch_log_out_of_gas(&precompiles(), Mode::BatchSome) .expect_no_logs() - .execute_returns(Vec::new()); + .execute_returns(()); }) } @@ -566,7 +557,7 @@ fn batch_some_until_failure_log_out_of_gas() { ExtBuilder::default().build().execute_with(|| { batch_log_out_of_gas(&precompiles(), Mode::BatchSomeUntilFailure) .expect_no_logs() - .execute_returns(Vec::new()); + .execute_returns(()); }) } @@ -604,7 +595,7 @@ fn batch_some_call_out_of_gas() { ExtBuilder::default().build().execute_with(|| { batch_call_out_of_gas(&precompiles(), Mode::BatchSome) .expect_log(log_subcall_failed(Batch, 0)) - .execute_returns(Vec::new()); + .execute_returns(()); }) } @@ -613,7 +604,7 @@ fn batch_some_until_failure_call_out_of_gas() { ExtBuilder::default().build().execute_with(|| { batch_call_out_of_gas(&precompiles(), Mode::BatchSomeUntilFailure) .expect_log(log_subcall_failed(Batch, 0)) - .execute_returns(Vec::new()); + .execute_returns(()); }) } @@ -654,7 +645,7 @@ fn batch_some_gas_limit() { batch_gas_limit(&precompiles(), Mode::BatchSome) .expect_log(log_subcall_failed(Batch, 0)) .expect_cost(return_log_cost) - .execute_returns(Vec::new()); + .execute_returns(()); }) } @@ -663,7 +654,7 @@ fn batch_some_until_failure_gas_limit() { ExtBuilder::default().build().execute_with(|| { batch_gas_limit(&precompiles(), Mode::BatchSomeUntilFailure) .expect_log(log_subcall_failed(Batch, 0)) - .execute_returns(Vec::new()); + .execute_returns(()); }) } @@ -1098,25 +1089,5 @@ fn batch_is_not_callable_by_dummy_code() { #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { - for file in ["Batch.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCall::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces(&["Batch.sol"], PCall::supports_selector) } diff --git a/precompiles/call-permit/src/lib.rs b/precompiles/call-permit/src/lib.rs index d0c63b1c0b..6e500bcdb0 100644 --- a/precompiles/call-permit/src/lib.rs +++ b/precompiles/call-permit/src/lib.rs @@ -25,7 +25,7 @@ use frame_support::{ traits::{ConstU32, Get, StorageInstance}, Blake2_128Concat, }; -use precompile_utils::{costs::call_cost, prelude::*}; +use precompile_utils::{evm::costs::call_cost, prelude::*}; use sp_core::{H160, H256, U256}; use sp_io::hashing::keccak_256; use sp_std::vec::Vec; @@ -86,13 +86,13 @@ where let version: H256 = keccak256!("1").into(); let chain_id: U256 = Runtime::ChainId::get().into(); - let domain_separator_inner = EvmDataWriter::new() - .write(H256::from(PERMIT_DOMAIN)) - .write(name) - .write(version) - .write(chain_id) - .write(Address(address)) - .build(); + let domain_separator_inner = solidity::encode_arguments(( + H256::from(PERMIT_DOMAIN), + name, + version, + chain_id, + Address(address), + )); keccak_256(&domain_separator_inner).into() } @@ -109,17 +109,17 @@ where ) -> [u8; 32] { let domain_separator = Self::compute_domain_separator(address); - let permit_content = EvmDataWriter::new() - .write(H256::from(PERMIT_TYPEHASH)) - .write(Address(from)) - .write(Address(to)) - .write(value) + let permit_content = solidity::encode_arguments(( + H256::from(PERMIT_TYPEHASH), + Address(from), + Address(to), + value, // bytes are encoded as the keccak_256 of the content - .write(H256::from(keccak_256(&data))) - .write(gaslimit) - .write(nonce) - .write(deadline) - .build(); + H256::from(keccak_256(&data)), + gaslimit, + nonce, + deadline, + )); let permit_content = keccak_256(&permit_content); let mut pre_digest = Vec::with_capacity(2 + 32 + 32); pre_digest.extend_from_slice(b"\x19\x01"); diff --git a/precompiles/call-permit/src/tests.rs b/precompiles/call-permit/src/tests.rs index 07cf6bcc8a..bbf9702f6d 100644 --- a/precompiles/call-permit/src/tests.rs +++ b/precompiles/call-permit/src/tests.rs @@ -18,10 +18,10 @@ use crate::{ mock::{CallPermit, ExtBuilder, PCall, Precompiles, PrecompilesValue, Runtime}, CallPermitPrecompile, }; -use evm::ExitReason; -use fp_evm::{ExitRevert, ExitSucceed}; use libsecp256k1::{sign, Message, SecretKey}; -use precompile_utils::{costs::call_cost, encoded_revert, prelude::*, testing::*}; +use precompile_utils::{ + evm::costs::call_cost, prelude::*, solidity::revert::revert_as_bytes, testing::*, +}; use sp_core::{H160, H256, U256}; fn precompiles() -> Precompiles { @@ -91,7 +91,7 @@ fn valid_permit_returns() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); let call_cost = call_cost(value, ::config()); @@ -138,20 +138,16 @@ fn valid_permit_returns() { assert_eq!(&input, b"Test"); SubcallOutput { - reason: ExitReason::Succeed(ExitSucceed::Returned), output: b"TEST".to_vec(), cost: 13, logs: vec![log1(Bob, H256::repeat_byte(0x11), vec![])], + ..SubcallOutput::succeed() } }) .with_target_gas(Some(call_cost + 100_000 + dispatch_cost())) .expect_cost(call_cost + 13 + dispatch_cost()) .expect_log(log1(Bob, H256::repeat_byte(0x11), vec![])) - .execute_returns( - EvmDataWriter::new() - .write(UnboundedBytes::from(b"TEST")) - .build(), - ); + .execute_returns(UnboundedBytes::from(b"TEST")); }) } @@ -194,7 +190,7 @@ fn valid_permit_reverts() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); let call_cost = call_cost(value, ::config()); @@ -241,10 +237,9 @@ fn valid_permit_reverts() { assert_eq!(&input, b"Test"); SubcallOutput { - reason: ExitReason::Revert(ExitRevert::Reverted), - output: encoded_revert(b"TEST"), + output: revert_as_bytes("TEST"), cost: 13, - logs: vec![], + ..SubcallOutput::revert() } }) .with_target_gas(Some(call_cost + 100_000 + dispatch_cost())) @@ -293,7 +288,7 @@ fn invalid_permit_nonce() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); let call_cost = call_cost(value, ::config()); @@ -359,7 +354,7 @@ fn invalid_permit_gas_limit_too_low() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); let call_cost = call_cost(value, ::config()); @@ -427,7 +422,7 @@ fn invalid_permit_gas_limit_overflow() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); precompiles() .prepare_test( @@ -615,7 +610,7 @@ fn valid_permit_returns_with_metamask_signed_data() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(U256::from(0u8)); + .execute_returns(U256::from(0u8)); let call_cost = call_cost(value, ::config()); @@ -662,44 +657,20 @@ fn valid_permit_returns_with_metamask_signed_data() { assert_eq!(&input, &data); SubcallOutput { - reason: ExitReason::Succeed(ExitSucceed::Returned), output: b"TEST".to_vec(), cost: 13, logs: vec![log1(Bob, H256::repeat_byte(0x11), vec![])], + ..SubcallOutput::succeed() } }) .with_target_gas(Some(call_cost + 100_000 + dispatch_cost())) .expect_cost(call_cost + 13 + dispatch_cost()) .expect_log(log1(Bob, H256::repeat_byte(0x11), vec![])) - .execute_returns( - EvmDataWriter::new() - .write(UnboundedBytes::from(b"TEST")) - .build(), - ); + .execute_returns(UnboundedBytes::from(b"TEST")); }) } #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { - for file in ["CallPermit.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCall::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces(&["CallPermit.sol"], PCall::supports_selector) } diff --git a/precompiles/collective/src/lib.rs b/precompiles/collective/src/lib.rs index dfc297720e..217b7f453b 100644 --- a/precompiles/collective/src/lib.rs +++ b/precompiles/collective/src/lib.rs @@ -65,9 +65,9 @@ pub fn log_proposed( address.into(), SELECTOR_LOG_PROPOSED, who.into(), - H256::from_slice(&EvmDataWriter::new().write(index).build()), + H256::from_slice(&solidity::encode_arguments(index)), hash, - EvmDataWriter::new().write(threshold).build(), + solidity::encode_arguments(threshold), ) } @@ -77,7 +77,7 @@ pub fn log_voted(address: impl Into, who: impl Into, hash: H256, vot SELECTOR_LOG_VOTED, who.into(), hash, - EvmDataWriter::new().write(voted).build(), + solidity::encode_arguments(voted), ) } diff --git a/precompiles/collective/src/tests.rs b/precompiles/collective/src/tests.rs index cca3ce9535..02b95a4416 100644 --- a/precompiles/collective/src/tests.rs +++ b/precompiles/collective/src/tests.rs @@ -19,7 +19,7 @@ use crate::{ mock::{ExtBuilder, PCall, Precompiles, PrecompilesValue, Runtime, RuntimeOrigin}, }; use frame_support::{assert_ok, dispatch::Encode}; -use precompile_utils::{data::Address, testing::*}; +use precompile_utils::{solidity::codec::Address, testing::*}; use sp_core::{H160, H256}; use sp_runtime::DispatchError; @@ -29,27 +29,7 @@ fn precompiles() -> Precompiles { #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { - for file in ["Collective.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCall::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces(&["Collective.sol"], PCall::supports_selector) } #[test] @@ -229,7 +209,7 @@ fn member_can_make_instant_proposal() { }, ) .expect_log(log_executed(Precompile1, proposal_hash)) - .execute_returns_encoded(0u32); + .execute_returns(0u32); assert_event_emitted!(pallet_collective::Event::Executed { proposal_hash, @@ -260,7 +240,7 @@ fn member_can_make_delayed_proposal() { }, ) .expect_log(log_proposed(Precompile1, Bob, 0, proposal_hash, 2)) - .execute_returns_encoded(0u32); + .execute_returns(0u32); assert_event_emitted!(pallet_collective::Event::Proposed { account: Bob.into(), @@ -293,7 +273,7 @@ fn member_can_vote_on_proposal() { }, ) .expect_log(log_proposed(Precompile1, Bob, 0, proposal_hash, 2)) - .execute_returns_encoded(0u32); + .execute_returns(0u32); precompiles() .prepare_test( @@ -306,7 +286,7 @@ fn member_can_vote_on_proposal() { }, ) .expect_log(log_voted(Precompile1, Charlie, proposal_hash, true)) - .execute_returns(vec![]); + .execute_returns(()); assert_event_emitted!(pallet_collective::Event::Voted { account: Charlie.into(), @@ -341,7 +321,7 @@ fn cannot_close_if_not_enough_votes() { }, ) .expect_log(log_proposed(Precompile1, Bob, 0, proposal_hash, 2)) - .execute_returns_encoded(0u32); + .execute_returns(0u32); precompiles() .prepare_test( @@ -381,7 +361,7 @@ fn can_close_execute_if_enough_votes() { }, ) .expect_log(log_proposed(Precompile1, Bob, 0, proposal_hash, 2)) - .execute_returns_encoded(0u32); + .execute_returns(0u32); precompiles() .prepare_test( @@ -394,7 +374,7 @@ fn can_close_execute_if_enough_votes() { }, ) .expect_log(log_voted(Precompile1, Bob, proposal_hash, true)) - .execute_returns(vec![]); + .execute_returns(()); precompiles() .prepare_test( @@ -407,7 +387,7 @@ fn can_close_execute_if_enough_votes() { }, ) .expect_log(log_voted(Precompile1, Charlie, proposal_hash, true)) - .execute_returns(vec![]); + .execute_returns(()); precompiles() .prepare_test( @@ -421,7 +401,7 @@ fn can_close_execute_if_enough_votes() { }, ) .expect_log(log_executed(Precompile1, proposal_hash)) - .execute_returns_encoded(true); + .execute_returns(true); assert_event_emitted!(pallet_collective::Event::Closed { proposal_hash, @@ -469,7 +449,7 @@ fn can_close_refuse_if_enough_votes() { }, ) .expect_log(log_proposed(Precompile1, Bob, 0, proposal_hash, 2)) - .execute_returns_encoded(0u32); + .execute_returns(0u32); precompiles() .prepare_test( @@ -482,7 +462,7 @@ fn can_close_refuse_if_enough_votes() { }, ) .expect_log(log_voted(Precompile1, Bob, proposal_hash, false)) - .execute_returns(vec![]); + .execute_returns(()); precompiles() .prepare_test( @@ -495,7 +475,7 @@ fn can_close_refuse_if_enough_votes() { }, ) .expect_log(log_voted(Precompile1, Charlie, proposal_hash, false)) - .execute_returns(vec![]); + .execute_returns(()); precompiles() .prepare_test( @@ -509,7 +489,7 @@ fn can_close_refuse_if_enough_votes() { }, ) .expect_log(log_closed(Precompile1, proposal_hash)) - .execute_returns_encoded(false); + .execute_returns(false); assert_event_emitted!(pallet_collective::Event::Closed { proposal_hash, @@ -543,7 +523,7 @@ fn multiple_propose_increase_index() { }, ) .expect_log(log_proposed(Precompile1, Bob, 0, proposal_hash, 2)) - .execute_returns_encoded(0u32); + .execute_returns(0u32); let proposal = pallet_treasury::Call::::spend { amount: 2, @@ -563,7 +543,7 @@ fn multiple_propose_increase_index() { }, ) .expect_log(log_proposed(Precompile1, Bob, 1, proposal_hash, 2)) - .execute_returns_encoded(1u32); + .execute_returns(1u32); }); } @@ -573,7 +553,7 @@ fn view_members() { precompiles() .prepare_test(Bob, Precompile1, PCall::members {}) .expect_no_logs() - .execute_returns_encoded(vec![Address(Bob.into()), Address(Charlie.into())]); + .execute_returns(vec![Address(Bob.into()), Address(Charlie.into())]); }); } @@ -583,7 +563,7 @@ fn view_no_prime() { precompiles() .prepare_test(Bob, Precompile1, PCall::prime {}) .expect_no_logs() - .execute_returns_encoded(Address(H160::zero())); + .execute_returns(Address(H160::zero())); }); } @@ -603,7 +583,7 @@ fn view_some_prime() { precompiles() .prepare_test(Bob, Precompile1, PCall::prime {}) .expect_no_logs() - .execute_returns_encoded(Address(Alice.into())); + .execute_returns(Address(Alice.into())); }); } @@ -619,7 +599,7 @@ fn view_is_member() { }, ) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); precompiles() .prepare_test( @@ -630,6 +610,6 @@ fn view_is_member() { }, ) .expect_no_logs() - .execute_returns_encoded(false); + .execute_returns(false); }); } diff --git a/precompiles/conviction-voting/src/lib.rs b/precompiles/conviction-voting/src/lib.rs index 8aae1863fa..aa04b11c4b 100644 --- a/precompiles/conviction-voting/src/lib.rs +++ b/precompiles/conviction-voting/src/lib.rs @@ -25,7 +25,7 @@ use pallet_conviction_voting::{ VotingFor, }; use pallet_evm::{AddressMapping, Log}; -use precompile_utils::{data::String, prelude::*}; +use precompile_utils::prelude::*; use sp_core::{H160, H256, U256}; use sp_runtime::traits::StaticLookup; use sp_std::marker::PhantomData; @@ -255,10 +255,7 @@ where handle.context().address, SELECTOR_LOG_VOTE_REMOVED_FOR_TRACK, H256::from_low_u64_be(poll_index as u64), - EvmDataWriter::new() - .write::(track_id) - .write::
(Address(caller)) - .build(), + solidity::encode_event_data((track_id, Address(caller))), ), Some(Self::u16_to_track_id(track_id).in_field("trackId")?), ) @@ -273,9 +270,7 @@ where handle.context().address, SELECTOR_LOG_VOTE_REMOVED, H256::from_low_u64_be(poll_index as u64), - EvmDataWriter::new() - .write::
(Address(caller)) - .build(), + solidity::encode_event_data(Address(caller)), ), None, ) @@ -304,11 +299,7 @@ where handle.context().address, SELECTOR_LOG_VOTE_REMOVED_OTHER, H256::from_low_u64_be(poll_index as u64), // poll index, - EvmDataWriter::new() - .write::
(Address(caller)) - .write::
(target) - .write::(track_id) - .build(), + solidity::encode_event_data((Address(caller), target, track_id)), ); handle.record_log_costs(&[&event])?; @@ -353,12 +344,7 @@ where handle.context().address, SELECTOR_LOG_DELEGATED, H256::from_low_u64_be(track_id as u64), // track id, - EvmDataWriter::new() - .write::
(Address(caller)) - .write::
(representative) - .write::(amount) - .write::(conviction) - .build(), + solidity::encode_event_data((Address(caller), representative, amount, conviction)), ); handle.record_log_costs(&[&event])?; @@ -397,9 +383,7 @@ where handle.context().address, SELECTOR_LOG_UNDELEGATED, H256::from_low_u64_be(track_id as u64), // track id, - EvmDataWriter::new() - .write::
(Address(caller)) - .build(), + solidity::encode_event_data(Address(caller)), ); handle.record_log_costs(&[&event])?; @@ -422,7 +406,7 @@ where handle.context().address, SELECTOR_LOG_UNLOCKED, H256::from_low_u64_be(track_id as u64), // track id, - EvmDataWriter::new().write::
(target).build(), + solidity::encode_event_data(target), ); handle.record_log_costs(&[&event])?; @@ -527,12 +511,12 @@ where contract_addr, SELECTOR_LOG_VOTED, H256::from_low_u64_be(poll_index as u64), - EvmDataWriter::new() - .write::
(Address(caller)) - .write::(vote.aye) - .write::(balance) - .write::(vote.conviction.into()) - .build(), + solidity::encode_event_data(( + Address(caller), + vote.aye, + balance, + u8::from(vote.conviction), + )), ); ( AccountVote::Standard { @@ -547,11 +531,7 @@ where contract_addr, SELECTOR_LOG_VOTE_SPLIT, H256::from_low_u64_be(poll_index as u64), - EvmDataWriter::new() - .write::
(Address(caller)) - .write::(aye) - .write::(nay) - .build(), + solidity::encode_event_data((Address(caller), aye, nay)), ); ( AccountVote::Split { @@ -566,12 +546,7 @@ where contract_addr, SELECTOR_LOG_VOTE_SPLIT_ABSTAINED, H256::from_low_u64_be(poll_index as u64), - EvmDataWriter::new() - .write::
(Address(caller)) - .write::(aye) - .write::(nay) - .write::(abstain) - .build(), + solidity::encode_event_data((Address(caller), aye, nay, abstain)), ); ( AccountVote::SplitAbstain { @@ -679,13 +654,13 @@ where } } -#[derive(Default, EvmData)] +#[derive(Default, solidity::Codec)] pub struct OutputClassLock { track: u16, amount: U256, } -#[derive(Default, EvmData)] +#[derive(Default, solidity::Codec)] pub struct OutputVotingFor { is_casting: bool, is_delegating: bool, @@ -693,20 +668,20 @@ pub struct OutputVotingFor { delegating: OutputDelegating, } -#[derive(Default, EvmData)] +#[derive(Default, solidity::Codec)] pub struct OutputCasting { votes: Vec, delegations: Delegations, prior: PriorLock, } -#[derive(Default, EvmData)] +#[derive(Default, solidity::Codec)] pub struct PollAccountVote { poll_index: u32, account_vote: OutputAccountVote, } -#[derive(Default, EvmData)] +#[derive(Default, solidity::Codec)] pub struct OutputDelegating { balance: U256, target: Address, @@ -715,7 +690,7 @@ pub struct OutputDelegating { prior: PriorLock, } -#[derive(Default, EvmData)] +#[derive(Default, solidity::Codec)] pub struct OutputAccountVote { is_standard: bool, is_split: bool, @@ -725,38 +700,38 @@ pub struct OutputAccountVote { split_abstain: SplitAbstainVote, } -#[derive(Default, EvmData)] +#[derive(Default, solidity::Codec)] pub struct StandardVote { vote: OutputVote, balance: U256, } -#[derive(Default, EvmData)] +#[derive(Default, solidity::Codec)] pub struct OutputVote { aye: bool, conviction: u8, } -#[derive(Default, EvmData)] +#[derive(Default, solidity::Codec)] pub struct SplitVote { aye: U256, nay: U256, } -#[derive(Default, EvmData)] +#[derive(Default, solidity::Codec)] pub struct SplitAbstainVote { aye: U256, nay: U256, abstain: U256, } -#[derive(Default, EvmData)] +#[derive(Default, solidity::Codec)] pub struct Delegations { votes: U256, capital: U256, } -#[derive(Default, EvmData)] +#[derive(Default, solidity::Codec)] pub struct PriorLock { balance: U256, } diff --git a/precompiles/conviction-voting/src/tests.rs b/precompiles/conviction-voting/src/tests.rs index 6e012e9187..24e4ff55fe 100644 --- a/precompiles/conviction-voting/src/tests.rs +++ b/precompiles/conviction-voting/src/tests.rs @@ -18,7 +18,7 @@ use crate::{ SELECTOR_LOG_VOTED, SELECTOR_LOG_VOTE_REMOVED, SELECTOR_LOG_VOTE_REMOVED_FOR_TRACK, SELECTOR_LOG_VOTE_REMOVED_OTHER, SELECTOR_LOG_VOTE_SPLIT, SELECTOR_LOG_VOTE_SPLIT_ABSTAINED, }; -use precompile_utils::{prelude::*, testing::*, EvmDataWriter}; +use precompile_utils::{prelude::*, testing::*}; use frame_support::{assert_ok, dispatch::Dispatchable}; use pallet_evm::{Call as EvmCall, Event as EvmEvent}; @@ -47,27 +47,10 @@ fn evm_call(input: Vec) -> EvmCall { #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { - for file in ["ConvictionVoting.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCall::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces( + &["ConvictionVoting.sol"], + PCall::supports_selector, + ) } fn standard_vote( @@ -139,12 +122,12 @@ fn standard_vote_logs_work() { Precompile1, SELECTOR_LOG_VOTED, H256::from_low_u64_be(ONGOING_POLL_INDEX as u64), - EvmDataWriter::new() - .write::
(H160::from(Alice).into()) // caller - .write::(true) // vote - .write::(100_000.into()) // amount - .write::(0) // conviction - .build(), + solidity::encode_event_data(( + Address(Alice.into()), // caller, + true, // vote + U256::from(100_000), // amount + 0u8, // conviction + )), ), } .into(), @@ -153,12 +136,12 @@ fn standard_vote_logs_work() { Precompile1, SELECTOR_LOG_VOTED, H256::from_low_u64_be(ONGOING_POLL_INDEX as u64), - EvmDataWriter::new() - .write::
(H160::from(Alice).into()) // caller - .write::(false) // vote - .write::(99_000.into()) // amount - .write::(1) // conviction - .build(), + solidity::encode_event_data(( + Address(Alice.into()), // caller + false, // vote, + U256::from(99_000), // amount + 1u8, // conviction + )), ), } .into(), @@ -197,11 +180,11 @@ fn split_vote_logs_work() { Precompile1, SELECTOR_LOG_VOTE_SPLIT, H256::from_low_u64_be(ONGOING_POLL_INDEX as u64), - EvmDataWriter::new() - .write::
(H160::from(Alice).into()) // caller - .write::(20_000.into()) // aye vote - .write::(30_000.into()) // nay vote - .build(), + solidity::encode_event_data(( + Address(Alice.into()), // caller + U256::from(20_000), // aye vote + U256::from(30_000), // nay vote + )), ), } .into(), @@ -210,12 +193,12 @@ fn split_vote_logs_work() { Precompile1, SELECTOR_LOG_VOTE_SPLIT_ABSTAINED, H256::from_low_u64_be(ONGOING_POLL_INDEX as u64), - EvmDataWriter::new() - .write::
(H160::from(Alice).into()) // caller - .write::(20_000.into()) // aye vote - .write::(20_000.into()) // nay vote - .write::(10_000.into()) // abstain vote - .build(), + solidity::encode_event_data(( + Address(Alice.into()), // caller, + U256::from(20_000), // aye vote + U256::from(20_000), // nay vote + U256::from(10_000), // abstain vote + )), ), } .into(), @@ -254,9 +237,7 @@ fn remove_vote_logs_work() { Precompile1, SELECTOR_LOG_VOTE_REMOVED, H256::from_low_u64_be(ONGOING_POLL_INDEX as u64), - EvmDataWriter::new() - .write::
(H160::from(Alice).into()) // caller - .build(), + solidity::encode_event_data(Address(Alice.into())) // caller ), } .into() @@ -288,10 +269,10 @@ fn remove_vote_for_track_logs_work() { Precompile1, SELECTOR_LOG_VOTE_REMOVED_FOR_TRACK, H256::from_low_u64_be(ONGOING_POLL_INDEX as u64), - EvmDataWriter::new() - .write::(0u16) - .write::
(H160::from(Alice).into()) // caller - .build(), + solidity::encode_event_data(( + 0u16, + Address(Alice.into()) // caller + )) ), } .into() @@ -324,11 +305,11 @@ fn remove_other_vote_logs_work() { Precompile1, SELECTOR_LOG_VOTE_REMOVED_OTHER, H256::from_low_u64_be(ONGOING_POLL_INDEX as u64), - EvmDataWriter::new() - .write::
(H160::from(Alice).into()) // caller - .write::
(H160::from(Alice).into()) // target - .write::(0u16) // track id - .build(), + solidity::encode_event_data(( + Address(Alice.into()), // caller + Address(Alice.into()), // target + 0u16, // track id + )) ), } .into() @@ -359,12 +340,12 @@ fn delegate_undelegate_logs_work() { Precompile1, SELECTOR_LOG_DELEGATED, H256::from_low_u64_be(0 as u64), // track id - EvmDataWriter::new() - .write::
(H160::from(Alice).into()) // from - .write::
(H160::from(Bob).into()) // to - .write::(100_000.into()) // amount - .write::(0u8) // conviction - .build(), + solidity::encode_event_data(( + Address(Alice.into()), // from + Address(Bob.into()), // to + U256::from(100_000), // amount + 0u8 // conviction + )) ), } .into() @@ -380,10 +361,8 @@ fn delegate_undelegate_logs_work() { log: log2( Precompile1, SELECTOR_LOG_UNDELEGATED, - H256::from_low_u64_be(0 as u64), // track id - EvmDataWriter::new() - .write::
(H160::from(Alice).into()) // caller - .build(), + H256::from_low_u64_be(0 as u64), // track id + solidity::encode_event_data(Address(Alice.into())) // caller ), } .into() @@ -422,9 +401,7 @@ fn unlock_logs_work() { Precompile1, SELECTOR_LOG_UNLOCKED, H256::from_low_u64_be(0 as u64), // track id - EvmDataWriter::new() - .write::
(H160::from(Alice).into()) // caller - .build(), + solidity::encode_event_data(Address(Alice.into())) ), } .into() @@ -451,7 +428,7 @@ fn test_voting_for_returns_correct_value_for_standard_vote() { }, ) .expect_no_logs() - .execute_returns_encoded(crate::OutputVotingFor { + .execute_returns(crate::OutputVotingFor { is_casting: true, casting: crate::OutputCasting { votes: vec![crate::PollAccountVote { @@ -498,7 +475,7 @@ fn test_voting_for_returns_correct_value_for_split_vote() { }, ) .expect_no_logs() - .execute_returns_encoded(crate::OutputVotingFor { + .execute_returns(crate::OutputVotingFor { is_casting: true, casting: crate::OutputCasting { votes: vec![crate::PollAccountVote { @@ -546,7 +523,7 @@ fn test_voting_for_returns_correct_value_for_split_abstain_vote() { }, ) .expect_no_logs() - .execute_returns_encoded(crate::OutputVotingFor { + .execute_returns(crate::OutputVotingFor { is_casting: true, casting: crate::OutputCasting { votes: vec![crate::PollAccountVote { @@ -590,7 +567,7 @@ fn test_class_locks_for_returns_correct_value() { }, ) .expect_no_logs() - .execute_returns_encoded(vec![crate::OutputClassLock { + .execute_returns(vec![crate::OutputClassLock { track: 0u16, amount: U256::from(100_000), }]); diff --git a/precompiles/crowdloan-rewards/src/tests.rs b/precompiles/crowdloan-rewards/src/tests.rs index 2eb3d0d23e..f8453d4e1c 100644 --- a/precompiles/crowdloan-rewards/src/tests.rs +++ b/precompiles/crowdloan-rewards/src/tests.rs @@ -98,7 +98,7 @@ fn is_contributor_returns_false() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(false); + .execute_returns(false); }); } @@ -140,7 +140,7 @@ fn is_contributor_returns_true() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); }); } @@ -225,12 +225,7 @@ fn reward_info_works() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(U256::from(50u64)) - .write(U256::from(10u64)) - .build(), - ); + .execute_returns((U256::from(50u64), U256::from(10u64))); }); } @@ -299,27 +294,10 @@ fn test_bound_checks_for_address_parsing() { #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { - for file in ["CrowdloanInterface.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCall::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces( + &["CrowdloanInterface.sol"], + PCall::supports_selector, + ) } #[test] @@ -329,7 +307,7 @@ fn test_deprecated_solidity_selectors_are_supported() { "reward_info(address)", "update_reward_address(address)", ] { - let selector = solidity::compute_selector(deprecated_function); + let selector = compute_selector(deprecated_function); if !PCall::supports_selector(selector) { panic!( "failed decoding selector 0x{:x} => '{}' as Action", diff --git a/precompiles/gmp/src/lib.rs b/precompiles/gmp/src/lib.rs index 9d26b75ca5..56585dd0a2 100644 --- a/precompiles/gmp/src/lib.rs +++ b/precompiles/gmp/src/lib.rs @@ -68,7 +68,7 @@ where From>, ::RuntimeCall: From>, Runtime: AccountIdToCurrencyId>, - XBalanceOf: TryFrom + Into + EvmData, + XBalanceOf: TryFrom + Into + solidity::Codec, { #[precompile::public("wormholeTransferERC20(bytes)")] pub fn wormhole_transfer_erc20( @@ -98,48 +98,45 @@ where let output = Self::call( handle, wormhole, - EvmDataWriter::new_with_selector(PARSE_VM_SELECTOR) - .write(wormhole_vaa.clone()) - .build(), + solidity::encode_with_selector(PARSE_VM_SELECTOR, wormhole_vaa.clone()), )?; - let mut reader = EvmDataReader::new(&output[..]); - let wormhole_vm: WormholeVM = reader.read()?; + let wormhole_vm: WormholeVM = solidity::decode_return_value(&output[..])?; // get the bridge transfer data from the wormhole VM payload let output = Self::call( handle, wormhole_bridge, - EvmDataWriter::new_with_selector(PARSE_TRANSFER_WITH_PAYLOAD_SELECTOR) - .write(wormhole_vm.payload) - .build(), + solidity::encode_with_selector( + PARSE_TRANSFER_WITH_PAYLOAD_SELECTOR, + wormhole_vm.payload, + ), )?; - let mut reader = EvmDataReader::new(&output[..]); - let transfer_with_payload: WormholeTransferWithPayloadData = reader.read()?; + let transfer_with_payload: WormholeTransferWithPayloadData = + solidity::decode_return_value(&output[..])?; // get the wrapper for this asset by calling wrappedAsset() // TODO: this should only be done if needed (when token chain == our chain) let output = Self::call( handle, wormhole_bridge, - EvmDataWriter::new_with_selector(WRAPPED_ASSET_SELECTOR) - .write(transfer_with_payload.token_chain) - .write(transfer_with_payload.token_address) - .build(), + solidity::encode_with_selector( + WRAPPED_ASSET_SELECTOR, + ( + transfer_with_payload.token_chain, + transfer_with_payload.token_address, + ), + ), )?; - let mut reader = EvmDataReader::new(&output[..]); - let wrapped_address: Address = reader.read()?; + let wrapped_address: Address = solidity::decode_return_value(&output[..])?; log::debug!(target: "gmp-precompile", "wrapped token address: {:?}", wrapped_address); // query our "before" balance (our being this precompile) let output = Self::call( handle, wrapped_address.into(), - EvmDataWriter::new_with_selector(BALANCE_OF_SELECTOR) - .write(Address::from(handle.code_address())) - .build(), + solidity::encode_with_selector(BALANCE_OF_SELECTOR, Address(handle.code_address())), )?; - let mut reader = EvmDataReader::new(&output[..]); - let before_amount: U256 = reader.read()?; + let before_amount: U256 = solidity::decode_return_value(&output[..])?; log::debug!(target: "gmp-precompile", "before balance: {}", before_amount); // our inner-most payload should be a VersionedUserAction @@ -162,21 +159,19 @@ where Self::call( handle, wormhole_bridge, - EvmDataWriter::new_with_selector(COMPLETE_TRANSFER_WITH_PAYLOAD_SELECTOR) - .write(wormhole_vaa) - .build(), + solidity::encode_with_selector(COMPLETE_TRANSFER_WITH_PAYLOAD_SELECTOR, wormhole_vaa), )?; // query our "after" balance (our being this precompile) let output = Self::call( handle, wrapped_address.into(), - EvmDataWriter::new_with_selector(BALANCE_OF_SELECTOR) - .write(Address::from(handle.code_address())) - .build(), + solidity::encode_with_selector( + BALANCE_OF_SELECTOR, + Address::from(handle.code_address()), + ), )?; - let mut reader = EvmDataReader::new(&output[..]); - let after_amount: U256 = reader.read()?; + let after_amount: U256 = solidity::decode_return_value(&output[..])?; log::debug!(target: "gmp-precompile", "after balance: {}", after_amount); let amount_transferred = after_amount.saturating_sub(before_amount); diff --git a/precompiles/gmp/src/tests.rs b/precompiles/gmp/src/tests.rs index 4e8ea3af84..2e9cff642f 100644 --- a/precompiles/gmp/src/tests.rs +++ b/precompiles/gmp/src/tests.rs @@ -19,26 +19,5 @@ use precompile_utils::testing::*; #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { - for file in ["Gmp.sol"] { - // assert_eq!(solidity::get_selectors(file).len(), 2); - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCall::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces(&["Gmp.sol"], PCall::supports_selector) } diff --git a/precompiles/gmp/src/types.rs b/precompiles/gmp/src/types.rs index 81058eaf67..76e2f3dc40 100644 --- a/precompiles/gmp/src/types.rs +++ b/precompiles/gmp/src/types.rs @@ -19,10 +19,7 @@ #![cfg_attr(not(feature = "std"), no_std)] use parity_scale_codec::{Decode, Encode}; -use precompile_utils::{ - data::{BoundedBytes, String}, - EvmData, -}; +use precompile_utils::prelude::*; use sp_core::{H256, U256}; use sp_std::vec::Vec; use xcm::latest::MultiLocation; @@ -48,7 +45,7 @@ pub enum VersionedUserAction { // in the Wormhole Ethereum contracts. // // https://github.com/wormhole-foundation/wormhole/blob/main/ethereum/contracts/Structs.sol -#[derive(Debug, EvmData)] +#[derive(Debug, solidity::Codec)] pub struct WormholeVM { pub version: u8, pub timestamp: u32, @@ -65,7 +62,7 @@ pub struct WormholeVM { } // Struct representing a Wormhole Signature struct -#[derive(Debug, EvmData)] +#[derive(Debug, solidity::Codec)] pub struct WormholeSignature { pub r: U256, pub s: U256, @@ -76,7 +73,7 @@ pub struct WormholeSignature { // Struct representing a wormhole "BridgeStructs.TransferWithPayload" struct // As with WormholeVM, the main purpose of this struct is to decode the ABI encoded struct when it // returned from calls to Wormhole Ethereum contracts. -#[derive(Debug, EvmData)] +#[derive(Debug, solidity::Codec)] pub struct WormholeTransferWithPayloadData { pub payload_id: u8, pub amount: U256, diff --git a/precompiles/pallet-democracy/src/lib.rs b/precompiles/pallet-democracy/src/lib.rs index 21e075ecf2..6ac516db07 100644 --- a/precompiles/pallet-democracy/src/lib.rs +++ b/precompiles/pallet-democracy/src/lib.rs @@ -81,7 +81,8 @@ where + pallet_evm::Config + frame_system::Config + pallet_preimage::Config, - BalanceOf: TryFrom + TryInto + Into + Debug + EvmData, + U256: From>, + BalanceOf: TryFrom + TryInto + Into + Debug + solidity::Codec, Runtime::RuntimeCall: Dispatchable + GetDispatchInfo, ::RuntimeOrigin: From>, Runtime::RuntimeCall: From>, @@ -107,7 +108,7 @@ where #[precompile::view] fn deposit_of( handle: &mut impl PrecompileHandle, - prop_index: SolidityConvert, + prop_index: Convert, ) -> EvmResult { let prop_index = prop_index.converted(); @@ -226,7 +227,7 @@ where handle.context().address, SELECTOR_LOG_PROPOSED, H256::from_low_u64_be(prop_count as u64), // proposal index, - EvmDataWriter::new().write::(value.into()).build(), + solidity::encode_event_data(U256::from(value)), ) .record(handle)?; @@ -236,8 +237,8 @@ where #[precompile::public("second(uint256,uint256)")] fn second( handle: &mut impl PrecompileHandle, - prop_index: SolidityConvert, - seconds_upper_bound: SolidityConvert, + prop_index: Convert, + seconds_upper_bound: Convert, ) -> EvmResult { handle.record_log_costs_manual(2, 32)?; let prop_index = prop_index.converted(); @@ -259,9 +260,7 @@ where handle.context().address, SELECTOR_LOG_SECONDED, H256::from_low_u64_be(prop_index as u64), // proposal index, - EvmDataWriter::new() - .write::
(handle.context().caller.into()) - .build(), + solidity::encode_event_data(Address(handle.context().caller)), ) .record(handle)?; @@ -272,10 +271,10 @@ where #[precompile::public("standard_vote(uint256,bool,uint256,uint256)")] fn standard_vote( handle: &mut impl PrecompileHandle, - ref_index: SolidityConvert, + ref_index: Convert, aye: bool, vote_amount: U256, - conviction: SolidityConvert, + conviction: Convert, ) -> EvmResult { handle.record_log_costs_manual(2, 32 * 4)?; let ref_index = ref_index.converted(); @@ -309,12 +308,12 @@ where handle.context().address, SELECTOR_LOG_STANDARD_VOTE, H256::from_low_u64_be(ref_index as u64), // referendum index, - EvmDataWriter::new() - .write::
(handle.context().caller.into()) - .write::(aye) - .write::(vote_amount) - .write::(conviction.converted()) - .build(), + solidity::encode_event_data(( + Address(handle.context().caller), + aye, + vote_amount, + conviction.converted(), + )), ) .record(handle)?; @@ -323,10 +322,7 @@ where #[precompile::public("removeVote(uint256)")] #[precompile::public("remove_vote(uint256)")] - fn remove_vote( - handle: &mut impl PrecompileHandle, - ref_index: SolidityConvert, - ) -> EvmResult { + fn remove_vote(handle: &mut impl PrecompileHandle, ref_index: Convert) -> EvmResult { let ref_index: u32 = ref_index.converted(); log::trace!( @@ -347,7 +343,7 @@ where fn delegate( handle: &mut impl PrecompileHandle, representative: Address, - conviction: SolidityConvert, + conviction: Convert, amount: U256, ) -> EvmResult { handle.record_log_costs_manual(2, 32)?; @@ -377,9 +373,7 @@ where handle.context().address, SELECTOR_LOG_DELEGATED, handle.context().caller, - EvmDataWriter::new() - .write::
(representative) - .build(), + solidity::encode_event_data(representative), ) .record(handle)?; diff --git a/precompiles/pallet-democracy/src/tests.rs b/precompiles/pallet-democracy/src/tests.rs index 1198e8ea63..6b85c08dee 100644 --- a/precompiles/pallet-democracy/src/tests.rs +++ b/precompiles/pallet-democracy/src/tests.rs @@ -122,7 +122,7 @@ fn prop_count_zero() { .prepare_test(Alice, Precompile1, PCall::public_prop_count {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns([0u8; 32].into()) + .execute_returns(U256::zero()) }); } @@ -143,7 +143,7 @@ fn prop_count_non_zero() { .prepare_test(Alice, Precompile1, PCall::public_prop_count {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(1u32); + .execute_returns(1u32); }); } @@ -172,7 +172,7 @@ fn deposit_of_non_zero() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(1000u32); + .execute_returns(1000u32); }); } @@ -198,7 +198,7 @@ fn lowest_unbaked_zero() { .prepare_test(Alice, Precompile1, PCall::lowest_unbaked {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(0u32); + .execute_returns(0u32); }); } @@ -275,7 +275,7 @@ fn lowest_unbaked_non_zero() { .prepare_test(Alice, Precompile1, PCall::lowest_unbaked {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(1u32); + .execute_returns(1u32); }); } @@ -310,7 +310,7 @@ fn ongoing_ref_info_works() { PCall::ongoing_referendum_info { ref_index: 0 }, ) .expect_no_logs() - .execute_returns_encoded(( + .execute_returns(( U256::from(11), // end hash, // hash 2u8, // threshold type @@ -412,7 +412,7 @@ fn finished_ref_info_works() { PCall::finished_referendum_info { ref_index: 0 }, ) .expect_no_logs() - .execute_returns_encoded((true, U256::from(11))); + .execute_returns((true, U256::from(11))); }) } @@ -502,7 +502,7 @@ fn propose_works() { Precompile1, SELECTOR_LOG_PROPOSED, H256::zero(), // proposal index, - EvmDataWriter::new().write::(100.into()).build(), + solidity::encode_event_data(U256::from(100)) ) } .into(), @@ -573,9 +573,7 @@ fn second_works() { Precompile1, SELECTOR_LOG_SECONDED, H256::zero(), // proposal index, - EvmDataWriter::new() - .write::
(H160::from(Alice).into()) - .build(), + solidity::encode_event_data(Address(Alice.into())) ) } .into(), @@ -641,12 +639,12 @@ fn standard_vote_aye_works() { Precompile1, SELECTOR_LOG_STANDARD_VOTE, H256::zero(), // referendum index, - EvmDataWriter::new() - .write::
(H160::from(Alice).into()) - .write::(true) - .write::(100000.into()) - .write::(0) - .build(), + solidity::encode_event_data(( + Address(Alice.into()), + true, + U256::from(100_000), + 0u8 + )) ), } .into(), @@ -736,12 +734,12 @@ fn standard_vote_nay_conviction_works() { Precompile1, SELECTOR_LOG_STANDARD_VOTE, H256::zero(), // referendum index, - EvmDataWriter::new() - .write::
(H160::from(Alice).into()) - .write::(false) - .write::(100000.into()) - .write::(3) - .build(), + solidity::encode_event_data(( + Address(Alice.into()), + false, + U256::from(100_000), + 3u8 + )) ), } .into(), @@ -924,9 +922,7 @@ fn delegate_works() { Precompile1, SELECTOR_LOG_DELEGATED, H160::from(Alice), - EvmDataWriter::new() - .write::
(H160::from(Bob).into()) - .build(), + solidity::encode_event_data(Address(Bob.into())) ), } .into(), @@ -1443,27 +1439,10 @@ fn cannot_note_imminent_preimage_before_it_is_actually_imminent() { #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { - for file in ["DemocracyInterface.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCall::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces( + &["DemocracyInterface.sol"], + PCall::supports_selector, + ) } #[test] @@ -1478,11 +1457,11 @@ fn test_deprecated_solidity_selectors_are_supported() { "note_preimage(bytes)", "note_imminent_preimage(bytes)", ] { - let selector = solidity::compute_selector(deprecated_function); + let selector = compute_selector(deprecated_function); if !PCall::supports_selector(selector) { panic!( - "failed decoding selector 0x{:x} => '{}' as Action", - selector, deprecated_function, + "deprecated selector {selector:x} for '{deprecated_function}' should be supported but\ + is not", ) } } diff --git a/precompiles/parachain-staking/src/lib.rs b/precompiles/parachain-staking/src/lib.rs index 14911de805..9ef0f883d6 100644 --- a/precompiles/parachain-staking/src/lib.rs +++ b/precompiles/parachain-staking/src/lib.rs @@ -53,7 +53,7 @@ where Runtime::RuntimeCall: Dispatchable + GetDispatchInfo, ::RuntimeOrigin: From>, Runtime::RuntimeCall: From>, - BalanceOf: TryFrom + Into + EvmData, + BalanceOf: TryFrom + Into + solidity::Codec, { // Constants #[precompile::public("minDelegation()")] @@ -75,10 +75,7 @@ where // Storage Getters #[precompile::public("points(uint256)")] #[precompile::view] - fn points( - handle: &mut impl PrecompileHandle, - round: SolidityConvert, - ) -> EvmResult { + fn points(handle: &mut impl PrecompileHandle, round: Convert) -> EvmResult { let round = round.converted(); // Fetch info. handle.record_cost(RuntimeHelper::::db_read_gas_cost())?; @@ -438,7 +435,7 @@ where fn join_candidates( handle: &mut impl PrecompileHandle, amount: U256, - candidate_count: SolidityConvert, + candidate_count: Convert, ) -> EvmResult { let amount = Self::u256_to_amount(amount).in_field("amount")?; let candidate_count = candidate_count.converted(); @@ -460,7 +457,7 @@ where #[precompile::public("schedule_leave_candidates(uint256)")] fn schedule_leave_candidates( handle: &mut impl PrecompileHandle, - candidate_count: SolidityConvert, + candidate_count: Convert, ) -> EvmResult { let candidate_count = candidate_count.converted(); @@ -481,7 +478,7 @@ where fn execute_leave_candidates( handle: &mut impl PrecompileHandle, candidate: Address, - candidate_count: SolidityConvert, + candidate_count: Convert, ) -> EvmResult { let candidate_count = candidate_count.converted(); let candidate = Runtime::AddressMapping::into_account_id(candidate.0); @@ -503,7 +500,7 @@ where #[precompile::public("cancel_leave_candidates(uint256)")] fn cancel_leave_candidates( handle: &mut impl PrecompileHandle, - candidate_count: SolidityConvert, + candidate_count: Convert, ) -> EvmResult { let candidate_count = candidate_count.converted(); @@ -611,8 +608,8 @@ where handle: &mut impl PrecompileHandle, candidate: Address, amount: U256, - candidate_delegation_count: SolidityConvert, - delegator_delegation_count: SolidityConvert, + candidate_delegation_count: Convert, + delegator_delegation_count: Convert, ) -> EvmResult { let amount = Self::u256_to_amount(amount).in_field("amount")?; let candidate_delegation_count = candidate_delegation_count.converted(); @@ -641,9 +638,9 @@ where candidate: Address, amount: U256, auto_compound: u8, - candidate_delegation_count: SolidityConvert, - candidate_auto_compounding_delegation_count: SolidityConvert, - delegator_delegation_count: SolidityConvert, + candidate_delegation_count: Convert, + candidate_auto_compounding_delegation_count: Convert, + delegator_delegation_count: Convert, ) -> EvmResult { if auto_compound > 100 { return Err( @@ -699,7 +696,7 @@ where fn execute_leave_delegators( handle: &mut impl PrecompileHandle, delegator: Address, - delegator_delegation_count: SolidityConvert, + delegator_delegation_count: Convert, ) -> EvmResult { let delegator = Runtime::AddressMapping::into_account_id(delegator.0); let delegator_delegation_count = delegator_delegation_count.converted(); @@ -842,8 +839,8 @@ where handle: &mut impl PrecompileHandle, candidate: Address, value: u8, - candidate_auto_compounding_delegation_count: SolidityConvert, - delegator_delegation_count: SolidityConvert, + candidate_auto_compounding_delegation_count: Convert, + delegator_delegation_count: Convert, ) -> EvmResult { if value > 100 { return Err( diff --git a/precompiles/parachain-staking/src/tests.rs b/precompiles/parachain-staking/src/tests.rs index 37dabdb338..aacc5db5da 100644 --- a/precompiles/parachain-staking/src/tests.rs +++ b/precompiles/parachain-staking/src/tests.rs @@ -154,7 +154,7 @@ fn min_delegation_works() { .prepare_test(Alice, Precompile1, PCall::min_delegation {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(3u32) + .execute_returns(3u32) }); } @@ -170,7 +170,7 @@ fn points_zero() { .prepare_test(Alice, Precompile1, PCall::points { round: 1.into() }) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(0u32); + .execute_returns(0u32); }); } @@ -188,7 +188,7 @@ fn points_non_zero() { .prepare_test(Alice, Precompile1, PCall::points { round: 1.into() }) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(100u32); + .execute_returns(100u32); }); } @@ -212,7 +212,7 @@ fn awarded_points_zero() { ) .expect_cost(0) .expect_no_logs() - .execute_returns_encoded(0u32); + .execute_returns(0u32); }); } @@ -237,7 +237,7 @@ fn awarded_points_non_zero() { ) .expect_cost(0) .expect_no_logs() - .execute_returns_encoded(100u32); + .execute_returns(100u32); }); } @@ -258,7 +258,7 @@ fn delegation_amount_zero() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(0u32); + .execute_returns(0u32); }); } @@ -281,7 +281,7 @@ fn delegation_amount_nonzero() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(1000u32); + .execute_returns(1000u32); }); } @@ -302,7 +302,7 @@ fn is_not_in_top_delegations_when_delegation_dne() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(false); + .execute_returns(false); }); } @@ -334,7 +334,7 @@ fn is_not_in_top_delegations_because_not_in_top() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(false); + .execute_returns(false); }); } @@ -357,7 +357,7 @@ fn is_in_top_delegations() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); }); } @@ -368,7 +368,7 @@ fn round_works() { .prepare_test(Alice, Precompile1, PCall::round {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(1u32); + .execute_returns(1u32); // test next `ROUNDS_TO_TEST` rounds const ROUNDS_TO_TEST: u32 = 10; @@ -382,7 +382,7 @@ fn round_works() { .prepare_test(Alice, Precompile1, PCall::round {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(current_round); + .execute_returns(current_round); } }); } @@ -415,7 +415,7 @@ fn candidate_delegation_count_works() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(3u32); + .execute_returns(3u32); }); } @@ -453,7 +453,7 @@ fn candidate_auto_compounding_delegation_count_works() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(1u32); + .execute_returns(1u32); }); } @@ -485,7 +485,7 @@ fn candidate_auto_compounding_elegation_count_works_with_zero() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(0u32); + .execute_returns(0u32); }); } @@ -515,7 +515,7 @@ fn delegator_delegation_count_works() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(2u32); + .execute_returns(2u32); }); } @@ -533,7 +533,7 @@ fn is_delegator_false() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(false); + .execute_returns(false); }); } @@ -556,7 +556,7 @@ fn is_delegator_true() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); }); } @@ -574,7 +574,7 @@ fn is_candidate_false() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(false); + .execute_returns(false); }); } @@ -596,7 +596,7 @@ fn is_candidate_true() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); }); } @@ -614,7 +614,7 @@ fn is_selected_candidate_false() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(false); + .execute_returns(false); }); } @@ -636,7 +636,7 @@ fn is_selected_candidate_true() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); }); } @@ -651,11 +651,7 @@ fn selected_candidates_works() { .prepare_test(Alice, Precompile1, PCall::selected_candidates {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(vec![Address(Alice.into())]) - .build(), - ); + .execute_returns(vec![Address(Alice.into())]); }); } @@ -683,7 +679,7 @@ fn delegation_request_is_pending_works() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(false); + .execute_returns(false); // Schedule Revoke request precompiles() @@ -696,7 +692,7 @@ fn delegation_request_is_pending_works() { ) .expect_cost(293131000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); // Assert that we have pending requests precompiles() @@ -710,7 +706,7 @@ fn delegation_request_is_pending_works() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); }) } @@ -729,7 +725,7 @@ fn delegation_request_is_pending_returns_false_for_non_existing_delegator() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(false); + .execute_returns(false); }) } @@ -751,7 +747,7 @@ fn candidate_exit_is_pending_works() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(false); + .execute_returns(false); // Schedule exit request precompiles() @@ -764,7 +760,7 @@ fn candidate_exit_is_pending_works() { ) .expect_cost(325075534) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); // Assert that we have pending exit precompiles() @@ -777,7 +773,7 @@ fn candidate_exit_is_pending_works() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); }) } @@ -795,7 +791,7 @@ fn candidate_exit_is_pending_returns_false_for_non_existing_delegator() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(false); + .execute_returns(false); }) } @@ -817,7 +813,7 @@ fn candidate_request_is_pending_works() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(false); + .execute_returns(false); // Schedule bond less request precompiles() @@ -828,7 +824,7 @@ fn candidate_request_is_pending_works() { ) .expect_cost(163239000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); // Assert that we have pending requests precompiles() @@ -841,7 +837,7 @@ fn candidate_request_is_pending_works() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); }) } @@ -859,7 +855,7 @@ fn candidate_request_is_pending_returns_false_for_non_existing_candidate() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns_encoded(false); + .execute_returns(false); }) } @@ -887,7 +883,7 @@ fn delegation_auto_compound_returns_value_if_set() { ) .expect_cost(0) .expect_no_logs() - .execute_returns_encoded(50u8); + .execute_returns(50u8); }) } @@ -910,7 +906,7 @@ fn delegation_auto_compound_returns_zero_if_not_set() { ) .expect_cost(0) .expect_no_logs() - .execute_returns_encoded(0u8); + .execute_returns(0u8); }) } @@ -1734,7 +1730,7 @@ fn get_delegator_total_staked_getter() { delegator: Address(Charlie.into()), }, ) - .execute_returns_encoded(U256::from(1_499)); + .execute_returns(U256::from(1_499)); }); } @@ -1757,7 +1753,7 @@ fn get_delegator_total_staked_getter_unknown() { delegator: Address(Charlie.into()), }, ) - .execute_returns_encoded(U256::zero()); + .execute_returns(U256::zero()); }); } @@ -1784,33 +1780,16 @@ fn get_candidate_total_counted_getter() { candidate: Address(Alice.into()), }, ) - .execute_returns_encoded(U256::from(2_000)); + .execute_returns(U256::from(2_000)); }); } #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { - for file in ["StakingInterface.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCall::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces( + &["StakingInterface.sol"], + PCall::supports_selector, + ) } #[test] @@ -1846,7 +1825,7 @@ fn test_deprecated_solidity_selectors_are_supported() { "execute_delegation_request(address,address)", "cancel_delegation_request(address)", ] { - let selector = solidity::compute_selector(deprecated_function); + let selector = compute_selector(deprecated_function); if !PCall::supports_selector(selector) { panic!( "failed decoding selector 0x{:x} => '{}' as Action", diff --git a/precompiles/precompile-registry/src/tests.rs b/precompiles/precompile-registry/src/tests.rs index 4d14427d7d..019ade37ee 100644 --- a/precompiles/precompile-registry/src/tests.rs +++ b/precompiles/precompile-registry/src/tests.rs @@ -68,7 +68,7 @@ mod is_precompile { }, ) .expect_no_logs() - .execute_returns_encoded(output); + .execute_returns(output); }); } @@ -111,7 +111,7 @@ mod is_active_precompile { }, ) .expect_no_logs() - .execute_returns_encoded(output); + .execute_returns(output); }); } @@ -156,7 +156,7 @@ mod update_account_code { ); if expect_changes { - tester.execute_returns_encoded(()); + tester.execute_returns(()); let new_code = pallet_evm::AccountCodes::::get(target_address); assert_eq!(&new_code, &[0x60, 0x00, 0x60, 0x00, 0xfd]); } else { @@ -195,25 +195,8 @@ mod update_account_code { #[test] fn test_solidity_interface() { - for file in ["PrecompileRegistry.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCall::supports_selector(selector) { - panic!( - "unsupported selector 0x{:x} => '{}' for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces( + &["PrecompileRegistry.sol"], + PCall::supports_selector, + ) } diff --git a/precompiles/preimage/src/lib.rs b/precompiles/preimage/src/lib.rs index 64e4c79987..6e80eac36a 100644 --- a/precompiles/preimage/src/lib.rs +++ b/precompiles/preimage/src/lib.rs @@ -69,7 +69,7 @@ where let event = log1( handle.context().address, SELECTOR_LOG_PREIMAGE_NOTED, - EvmDataWriter::new().write::(hash.into()).build(), + solidity::encode_arguments(H256::from(hash)), ); handle.record_log_costs(&[&event])?; let origin = Runtime::AddressMapping::into_account_id(handle.context().caller); @@ -91,7 +91,7 @@ where let event = log1( handle.context().address, SELECTOR_LOG_PREIMAGE_UNNOTED, - EvmDataWriter::new().write::(hash).build(), + solidity::encode_arguments(H256::from(hash)), ); handle.record_log_costs(&[&event])?; diff --git a/precompiles/preimage/src/tests.rs b/precompiles/preimage/src/tests.rs index 6d4cc14c8a..4bd8c7fda6 100644 --- a/precompiles/preimage/src/tests.rs +++ b/precompiles/preimage/src/tests.rs @@ -15,12 +15,12 @@ // along with Moonbeam. If not, see . use crate::mock::*; use crate::*; -use precompile_utils::{testing::*, EvmDataWriter}; +use precompile_utils::testing::*; use frame_support::{assert_ok, dispatch::Dispatchable}; use pallet_evm::{Call as EvmCall, Event as EvmEvent}; -use sp_core::{Hasher, H256, U256}; +use sp_core::{Hasher, U256}; fn evm_call(input: Vec) -> EvmCall { EvmCall::call { @@ -42,27 +42,7 @@ fn precompiles() -> Precompiles { #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { - for file in ["Preimage.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCall::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces(&["Preimage.sol"], PCall::supports_selector) } #[test] @@ -87,7 +67,7 @@ fn note_unnote_preimage_logs_work() { log: log1( Precompile1, SELECTOR_LOG_PREIMAGE_NOTED, - EvmDataWriter::new().write::(expected_hash).build(), + solidity::encode_event_data(expected_hash) ), } .into(), @@ -111,7 +91,7 @@ fn note_unnote_preimage_logs_work() { log: log1( Precompile1, SELECTOR_LOG_PREIMAGE_UNNOTED, - EvmDataWriter::new().write::(expected_hash).build(), + solidity::encode_event_data(expected_hash) ), } .into() @@ -136,6 +116,6 @@ fn note_preimage_returns_preimage_hash() { encoded_proposal: BoundedBytes::from(preimage), }, ) - .execute_returns_encoded(preimage_hash); + .execute_returns(preimage_hash); }) } diff --git a/precompiles/proxy/src/lib.rs b/precompiles/proxy/src/lib.rs index 40d7827802..352ca47a22 100644 --- a/precompiles/proxy/src/lib.rs +++ b/precompiles/proxy/src/lib.rs @@ -22,13 +22,9 @@ use frame_support::dispatch::{Dispatchable, GetDispatchInfo, PostDispatchInfo}; use pallet_evm::AddressMapping; use pallet_proxy::Call as ProxyCall; use pallet_proxy::Pallet as ProxyPallet; +use precompile_utils::precompile_set::{self, AddressType, SelectorFilter}; use precompile_utils::prelude::*; -use precompile_utils::{ - data::{Address, String}, - precompile_set::{self, AddressType, SelectorFilter}, -}; -use sp_core::H160; -use sp_core::U256; +use sp_core::{H160, U256}; use sp_runtime::{ codec::Decode, traits::{ConstU32, StaticLookup, Zero}, diff --git a/precompiles/proxy/src/tests.rs b/precompiles/proxy/src/tests.rs index 78db787da4..8d08ddd9d9 100644 --- a/precompiles/proxy/src/tests.rs +++ b/precompiles/proxy/src/tests.rs @@ -18,7 +18,6 @@ use crate::mock::{ AccountId, ExtBuilder, PCall, PrecompilesValue, ProxyType, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, }; -use evm::{ExitReason, ExitSucceed}; use frame_support::{assert_ok, dispatch::Dispatchable}; use pallet_evm::Call as EvmCall; use pallet_proxy::{ @@ -191,7 +190,7 @@ fn test_add_proxy_succeeds() { delay: 1, }, ) - .execute_returns(vec![]); + .execute_returns(()); assert_event_emitted!(RuntimeEvent::Proxy(ProxyEvent::ProxyAdded { delegator: Alice.into(), delegatee: Bob.into(), @@ -281,7 +280,7 @@ fn test_remove_proxy_succeeds() { delay: 0, }, ) - .execute_returns(vec![]); + .execute_returns(()); assert_event_emitted!(RuntimeEvent::Proxy(ProxyEvent::ProxyRemoved { delegator: Alice.into(), delegatee: Bob.into(), @@ -315,7 +314,7 @@ fn test_remove_proxies_succeeds() { PrecompilesValue::get() .prepare_test(Alice, Precompile1, PCall::remove_proxies {}) - .execute_returns(vec![]); + .execute_returns(()); let proxies = >::proxies(AccountId::from(Alice)).0; assert_eq!(proxies, vec![]) @@ -330,7 +329,7 @@ fn test_remove_proxies_succeeds_when_no_proxy_exists() { .execute_with(|| { PrecompilesValue::get() .prepare_test(Alice, Precompile1, PCall::remove_proxies {}) - .execute_returns(vec![]); + .execute_returns(()); let proxies = >::proxies(AccountId::from(Alice)).0; assert_eq!(proxies, vec![]) @@ -395,7 +394,7 @@ fn test_proxy_fails_if_call_filtered() { delay: 0, }, ) - .execute_returns(vec![]); + .execute_returns(()); // Trying to use delayed proxy without any announcement PrecompilesValue::get() @@ -429,7 +428,7 @@ fn test_is_proxy_returns_false_if_not_proxy() { delay: 0, }, ) - .execute_returns_encoded(false); + .execute_returns(false); }) } @@ -457,7 +456,7 @@ fn test_is_proxy_returns_false_if_proxy_type_incorrect() { delay: 0, }, ) - .execute_returns_encoded(false); + .execute_returns(false); }) } @@ -485,7 +484,7 @@ fn test_is_proxy_returns_false_if_proxy_delay_incorrect() { delay: 0, }, ) - .execute_returns_encoded(false); + .execute_returns(false); }) } @@ -513,35 +512,10 @@ fn test_is_proxy_returns_true_if_proxy() { delay: 1, }, ) - .execute_returns_encoded(true); + .execute_returns(true); }) } -#[test] -fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { - for file in ["Proxy.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCall::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } -} - #[test] fn test_nested_evm_bypass_proxy_should_allow_elevating_proxy_type() { ExtBuilder::default() @@ -639,7 +613,7 @@ fn succeed_if_called_by_precompile() { delay: 1, }, ) - .execute_returns(vec![]); + .execute_returns(()); }) } @@ -663,7 +637,7 @@ fn succeed_if_is_proxy_called_by_smart_contract() { delay: 1, }, ) - .execute_returns_encoded(false); + .execute_returns(false); }) } @@ -774,13 +748,13 @@ fn proxy_proxy_should_succeed_if_called_by_smart_contract() { inside2.set(true); SubcallOutput { - reason: ExitReason::Succeed(ExitSucceed::Returned), output: b"TEST".to_vec(), cost: 13, logs: vec![log1(Bob, H256::repeat_byte(0x11), vec![])], + ..SubcallOutput::succeed() } }) - .execute_returns_encoded(()); + .execute_returns(()); // Ensure that the subcall was actually called. // proxy.proxy does not propagate the return value, so we cannot check for the return @@ -848,12 +822,17 @@ fn proxy_proxy_should_fail_if_called_by_smart_contract_for_a_non_eoa_account() { inside2.set(true); SubcallOutput { - reason: ExitReason::Succeed(ExitSucceed::Returned), output: b"TEST".to_vec(), cost: 13, logs: vec![log1(Bob, H256::repeat_byte(0x11), vec![])], + ..SubcallOutput::succeed() } }) .execute_reverts(|output| output == b"real address must be EOA"); }) } + +#[test] +fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { + check_precompile_implements_solidity_interfaces(&["Proxy.sol"], PCall::supports_selector) +} diff --git a/precompiles/randomness/src/lib.rs b/precompiles/randomness/src/lib.rs index ae2aa4623f..85c3014651 100644 --- a/precompiles/randomness/src/lib.rs +++ b/precompiles/randomness/src/lib.rs @@ -27,7 +27,7 @@ use pallet_randomness::{ weights::{SubstrateWeight, WeightInfo}, BalanceOf, GetBabeData, Pallet, Request, RequestInfo, RequestState, RequestType, }; -use precompile_utils::{costs::call_cost, prelude::*}; +use precompile_utils::{evm::costs::call_cost, prelude::*}; use sp_core::{H160, H256, U256}; use sp_std::{marker::PhantomData, vec, vec::Vec}; @@ -138,10 +138,7 @@ fn provide_randomness( contract, None, // callback function selector: keccak256("rawFulfillRandomWords(uint256,uint256[])") - EvmDataWriter::new_with_selector(0x1fe543e3_u32) - .write(request_id) - .write(randomness) - .build(), + solidity::encode_with_selector(0x1fe543e3_u32, (request_id, randomness)), Some(gas_limit), false, &Context { @@ -199,7 +196,7 @@ where #[precompile::view] fn get_request_status( handle: &mut impl PrecompileHandle, - request_id: SolidityConvert, + request_id: Convert, ) -> EvmResult { // record cost of 2 DB reads handle.record_cost(RuntimeHelper::::db_read_gas_cost() * 2)?; @@ -225,7 +222,7 @@ where #[precompile::view] fn get_request( handle: &mut impl PrecompileHandle, - request_id: SolidityConvert, + request_id: Convert, ) -> EvmResult<( U256, // id Address, // refund address @@ -361,7 +358,7 @@ where gas_limit: u64, salt: H256, num_words: u8, - delay: SolidityConvert, + delay: Convert, ) -> EvmResult { handle.record_cost( REQUEST_RANDOMNESS_ESTIMATED_COST + RuntimeHelper::::db_read_gas_cost(), @@ -406,7 +403,7 @@ where #[precompile::public("fulfillRequest(uint256)")] fn fulfill_request( handle: &mut impl PrecompileHandle, - request_id: SolidityConvert, + request_id: Convert, ) -> EvmResult { let request_id = request_id.converted(); @@ -495,7 +492,7 @@ where #[precompile::public("increaseRequestFee(uint256,uint256)")] fn increase_request_fee( handle: &mut impl PrecompileHandle, - request_id: SolidityConvert, + request_id: Convert, fee_increase: U256, ) -> EvmResult { handle.record_cost(INCREASE_REQUEST_FEE_ESTIMATED_COST)?; @@ -516,7 +513,7 @@ where #[precompile::public("purgeExpiredRequest(uint256)")] fn purge_expired_request( handle: &mut impl PrecompileHandle, - request_id: SolidityConvert, + request_id: Convert, ) -> EvmResult { handle.record_cost(EXECUTE_EXPIRATION_ESTIMATED_COST)?; diff --git a/precompiles/randomness/src/solidity_types.rs b/precompiles/randomness/src/solidity_types.rs index fc5324f7a2..48b99f4e1c 100644 --- a/precompiles/randomness/src/solidity_types.rs +++ b/precompiles/randomness/src/solidity_types.rs @@ -15,7 +15,10 @@ // along with Moonbeam. If not, see . //! Solidity types for randomness precompile. -use precompile_utils::{data::String, prelude::*}; +use precompile_utils::{ + prelude::*, + solidity::codec::{Reader, Writer}, +}; pub enum RequestStatus { DoesNotExist, @@ -29,8 +32,8 @@ pub enum RandomnessSource { RelayBabeEpoch, } -impl EvmData for RequestStatus { - fn read(reader: &mut EvmDataReader) -> MayRevert { +impl solidity::Codec for RequestStatus { + fn read(reader: &mut Reader) -> MayRevert { match reader.read().in_field("variant")? { 0u8 => Ok(RequestStatus::DoesNotExist), 1u8 => Ok(RequestStatus::Pending), @@ -40,27 +43,27 @@ impl EvmData for RequestStatus { } } - fn write(writer: &mut EvmDataWriter, value: Self) { + fn write(writer: &mut Writer, value: Self) { let encoded: u8 = match value { RequestStatus::DoesNotExist => 0u8, RequestStatus::Pending => 1u8, RequestStatus::Ready => 2u8, RequestStatus::Expired => 3u8, }; - EvmData::write(writer, encoded); + solidity::Codec::write(writer, encoded); } fn has_static_size() -> bool { true } - fn solidity_type() -> String { - u8::solidity_type() + fn signature() -> String { + u8::signature() } } -impl EvmData for RandomnessSource { - fn read(reader: &mut EvmDataReader) -> MayRevert { +impl solidity::Codec for RandomnessSource { + fn read(reader: &mut Reader) -> MayRevert { match reader.read().in_field("variant")? { 0u8 => Ok(RandomnessSource::LocalVRF), 1u8 => Ok(RandomnessSource::RelayBabeEpoch), @@ -68,19 +71,19 @@ impl EvmData for RandomnessSource { } } - fn write(writer: &mut EvmDataWriter, value: Self) { + fn write(writer: &mut Writer, value: Self) { let encoded: u8 = match value { RandomnessSource::LocalVRF => 0u8, RandomnessSource::RelayBabeEpoch => 1u8, }; - EvmData::write(writer, encoded); + solidity::Codec::write(writer, encoded); } fn has_static_size() -> bool { true } - fn solidity_type() -> String { - u8::solidity_type() + fn signature() -> String { + u8::signature() } } diff --git a/precompiles/randomness/src/tests.rs b/precompiles/randomness/src/tests.rs index def097b7cd..671f2fe25b 100644 --- a/precompiles/randomness/src/tests.rs +++ b/precompiles/randomness/src/tests.rs @@ -16,9 +16,9 @@ //! Randomness precompile unit tests use crate::{mock::*, prepare_and_finish_fulfillment_gas_cost, subcall_overhead_gas_costs}; -use fp_evm::{ExitReason, ExitRevert, ExitSucceed, FeeCalculator}; +use fp_evm::FeeCalculator; use pallet_randomness::{Event as RandomnessEvent, RandomnessResults, RequestType}; -use precompile_utils::{assert_event_emitted, testing::*, EvmDataWriter}; +use precompile_utils::{assert_event_emitted, prelude::*, testing::*}; use sp_core::{H160, H256, U256}; #[test] @@ -71,27 +71,7 @@ fn modifiers() { #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { - for file in ["Randomness.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCall::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces(&["Randomness.sol"], PCall::supports_selector) } #[test] @@ -101,7 +81,7 @@ fn relay_epoch_index_works() { PrecompilesValue::get() .prepare_test(Alice, Precompile1, PCall::relay_epoch_index {}) - .execute_returns_encoded(1u64); + .execute_returns(1u64); }) } @@ -112,7 +92,7 @@ fn required_deposit_works() { PrecompilesValue::get() .prepare_test(Alice, Precompile1, PCall::required_deposit {}) - .execute_returns_encoded(U256::from(10)); + .execute_returns(U256::from(10)); }) } @@ -129,7 +109,7 @@ fn get_dne_request_status() { request_id: 1.into(), }, ) - .execute_returns_encoded(0u8); + .execute_returns(0u8); }) } @@ -146,14 +126,14 @@ fn get_pending_request_status() { Alice, Precompile1, PCall::request_babe_randomness { - refund_address: precompile_utils::data::Address(H160::from(Bob)), + refund_address: Address(Bob.into()), fee: U256::one(), gas_limit: 100u64, salt: H256::default(), num_words: 1u8, }, ) - .execute_returns([0u8; 32].into()); + .execute_returns(U256::zero()); PrecompilesValue::get() .prepare_test( @@ -163,7 +143,7 @@ fn get_pending_request_status() { request_id: 0.into(), }, ) - .execute_returns_encoded(1u8); + .execute_returns(1u8); }) } @@ -179,7 +159,7 @@ fn get_ready_request_status() { Alice, Precompile1, PCall::request_local_randomness { - refund_address: precompile_utils::data::Address(H160::from(Bob)), + refund_address: Address(Bob.into()), fee: U256::one(), gas_limit: 10u64, salt: H256::default(), @@ -187,7 +167,7 @@ fn get_ready_request_status() { delay: 2.into(), }, ) - .execute_returns([0u8; 32].into()); + .execute_returns(U256::zero()); // run to ready block System::set_block_number(3); // ready status @@ -199,7 +179,7 @@ fn get_ready_request_status() { request_id: 0.into(), }, ) - .execute_returns_encoded(2u8); + .execute_returns(2u8); }) } @@ -215,7 +195,7 @@ fn get_expired_request_status() { Alice, Precompile1, PCall::request_local_randomness { - refund_address: precompile_utils::data::Address(H160::from(Bob)), + refund_address: Address(Bob.into()), fee: U256::one(), gas_limit: 10u64, salt: H256::default(), @@ -223,7 +203,7 @@ fn get_expired_request_status() { delay: 2.into(), }, ) - .execute_returns([0u8; 32].into()); + .execute_returns(U256::zero()); // run to expired block System::set_block_number(21); // ready status @@ -235,7 +215,7 @@ fn get_expired_request_status() { request_id: 0.into(), }, ) - .execute_returns_encoded(3u8); + .execute_returns(3u8); }) } @@ -251,7 +231,7 @@ fn get_request_works() { Alice, Precompile1, PCall::request_local_randomness { - refund_address: precompile_utils::data::Address(H160::from(Bob)), + refund_address: Address(Bob.into()), fee: U256::one(), gas_limit: 100u64, salt: H256::default(), @@ -259,7 +239,7 @@ fn get_request_works() { delay: 2.into(), }, ) - .execute_returns([0u8; 32].into()); + .execute_returns(U256::zero()); // run to expired block System::set_block_number(21); // ready status @@ -271,23 +251,21 @@ fn get_request_works() { request_id: 0.into(), }, ) - .execute_returns( - EvmDataWriter::new() - .write(U256::zero()) - .write(precompile_utils::data::Address(H160::from(Bob))) - .write(precompile_utils::data::Address(H160::from(Alice))) - .write(U256::one()) - .write(U256::from(100)) - .write(H256::default()) - .write(1u8) - .write(0u8) - .write(3u32) - .write(0u64) - .write(21u32) - .write(0u64) - .write(3u8) - .build(), - ); + .execute_returns(( + U256::zero(), + Address(Bob.into()), + Address(Alice.into()), + U256::one(), + U256::from(100), + H256::default(), + 1u8, + 0u8, + 3u32, + 0u64, + 21u32, + 0u64, + 3u8, + )); }) } @@ -304,14 +282,14 @@ fn request_babe_randomness_works() { Alice, Precompile1, PCall::request_babe_randomness { - refund_address: precompile_utils::data::Address(H160::from(Bob)), + refund_address: Address(H160::from(Bob)), fee: U256::one(), gas_limit: 100u64, salt: H256::default(), num_words: 1u8, }, ) - .execute_returns([0u8; 32].into()); + .execute_returns(U256::zero()); assert_event_emitted!(RuntimeEvent::Randomness( RandomnessEvent::RandomnessRequestedBabeEpoch { id: 0, @@ -340,7 +318,7 @@ fn request_local_randomness_works() { Alice, Precompile1, PCall::request_local_randomness { - refund_address: precompile_utils::data::Address(H160::from(Bob)), + refund_address: Address(H160::from(Bob)), fee: U256::one(), gas_limit: 100u64, salt: H256::default(), @@ -348,7 +326,7 @@ fn request_local_randomness_works() { delay: 2.into(), }, ) - .execute_returns([0u8; 32].into()); + .execute_returns(U256::zero()); assert_event_emitted!(RuntimeEvent::Randomness( RandomnessEvent::RandomnessRequestedLocal { id: 0, @@ -381,7 +359,7 @@ fn fulfill_request_reverts_if_not_enough_gas() { Alice, Precompile1, PCall::request_local_randomness { - refund_address: precompile_utils::data::Address(H160::from(Bob)), + refund_address: Address(H160::from(Bob)), fee: U256::one(), gas_limit: request_gas_limit, salt: H256::default(), @@ -389,7 +367,7 @@ fn fulfill_request_reverts_if_not_enough_gas() { delay: 2.into(), }, ) - .execute_returns([0u8; 32].into()); + .execute_returns(U256::zero()); // run to ready block System::set_block_number(3); @@ -444,7 +422,7 @@ fn fulfill_request_works() { Alice, Precompile1, PCall::request_local_randomness { - refund_address: precompile_utils::data::Address(H160::from(Bob)), + refund_address: Address(H160::from(Bob)), fee: U256::one(), gas_limit: request_gas_limit, salt: H256::default(), @@ -452,7 +430,7 @@ fn fulfill_request_works() { delay: 2.into(), }, ) - .execute_returns([0u8; 32].into()); + .execute_returns(U256::zero()); // run to ready block System::set_block_number(3); // fill randomness results @@ -498,22 +476,24 @@ fn fulfill_request_works() { // callback function selector: keccak256("rawFulfillRandomWords(uint256,uint256[])") assert_eq!( &input, - &EvmDataWriter::new_with_selector(0x1fe543e3_u32) - .write(0u64) // request id - .write(random_words.clone()) - .build() + &solidity::encode_with_selector( + 0x1fe543e3_u32, + ( + 0u64, // request id + random_words.clone() + ) + ) ); SubcallOutput { - reason: ExitReason::Succeed(ExitSucceed::Returned), output: b"TEST".to_vec(), cost: subcall_used_gas, - logs: vec![], + ..SubcallOutput::succeed() } }) .with_target_gas(Some(total_cost)) .expect_log(crate::log_fulfillment_succeeded(Precompile1)) - .execute_returns_encoded(()); + .execute_returns(()); // correctly refunded assert_eq!( @@ -548,7 +528,7 @@ fn fulfill_request_works_with_higher_gas() { Alice, Precompile1, PCall::request_local_randomness { - refund_address: precompile_utils::data::Address(H160::from(Bob)), + refund_address: Address(H160::from(Bob)), fee: U256::one(), gas_limit: request_gas_limit, salt: H256::default(), @@ -556,7 +536,7 @@ fn fulfill_request_works_with_higher_gas() { delay: 2.into(), }, ) - .execute_returns([0u8; 32].into()); + .execute_returns(U256::zero()); // run to ready block System::set_block_number(3); @@ -604,22 +584,24 @@ fn fulfill_request_works_with_higher_gas() { // callback function selector: keccak256("rawFulfillRandomWords(uint256,uint256[])") assert_eq!( &input, - &EvmDataWriter::new_with_selector(0x1fe543e3_u32) - .write(0u64) // request id - .write(random_words.clone()) - .build() + &solidity::encode_with_selector( + 0x1fe543e3_u32, + ( + 0u64, // request id + random_words.clone(), + ) + ) ); SubcallOutput { - reason: ExitReason::Succeed(ExitSucceed::Returned), output: b"TEST".to_vec(), cost: subcall_used_gas, - logs: vec![], + ..SubcallOutput::succeed() } }) .with_target_gas(Some(total_cost + 10_000)) .expect_log(crate::log_fulfillment_succeeded(Precompile1)) - .execute_returns_encoded(()); + .execute_returns(()); // correctly refunded assert_eq!( @@ -654,7 +636,7 @@ fn fulfill_request_works_with_subcall_revert() { Alice, Precompile1, PCall::request_local_randomness { - refund_address: precompile_utils::data::Address(H160::from(Bob)), + refund_address: Address(H160::from(Bob)), fee: U256::one(), gas_limit: request_gas_limit, salt: H256::default(), @@ -662,7 +644,7 @@ fn fulfill_request_works_with_subcall_revert() { delay: 2.into(), }, ) - .execute_returns([0u8; 32].into()); + .execute_returns(U256::zero()); // run to ready block System::set_block_number(3); @@ -710,22 +692,23 @@ fn fulfill_request_works_with_subcall_revert() { // callback function selector: keccak256("rawFulfillRandomWords(uint256,uint256[])") assert_eq!( &input, - &EvmDataWriter::new_with_selector(0x1fe543e3_u32) - .write(0u64) // request id - .write(random_words.clone()) - .build() + &solidity::encode_with_selector( + 0x1fe543e3_u32, + ( + 0u64, // request id + random_words.clone() + ) + ) ); SubcallOutput { - reason: ExitReason::Revert(ExitRevert::Reverted), - output: vec![], cost: subcall_used_gas, - logs: vec![], + ..SubcallOutput::revert() } }) .with_target_gas(Some(total_cost)) .expect_log(crate::log_fulfillment_failed(Precompile1)) - .execute_returns_encoded(()); + .execute_returns(()); // correctly refunded assert_eq!( @@ -747,7 +730,7 @@ fn increase_request_fee_works() { Alice, Precompile1, PCall::request_local_randomness { - refund_address: precompile_utils::data::Address(H160::from(Bob)), + refund_address: Address(H160::from(Bob)), fee: U256::one(), gas_limit: 100u64, salt: H256::default(), @@ -755,7 +738,7 @@ fn increase_request_fee_works() { delay: 2.into(), }, ) - .execute_returns([0u8; 32].into()); + .execute_returns(U256::zero()); // increase request fee PrecompilesValue::get() .prepare_test( @@ -766,7 +749,7 @@ fn increase_request_fee_works() { fee_increase: 10.into(), }, ) - .execute_returns(vec![]); + .execute_returns(()); assert_event_emitted!(RuntimeEvent::Randomness( RandomnessEvent::RequestFeeIncreased { id: 0, new_fee: 11 } )); @@ -785,7 +768,7 @@ fn purge_expired_request_works() { Alice, Precompile1, PCall::request_local_randomness { - refund_address: precompile_utils::data::Address(H160::from(Bob)), + refund_address: Address(H160::from(Bob)), fee: U256::one(), gas_limit: 100u64, salt: H256::default(), @@ -793,7 +776,7 @@ fn purge_expired_request_works() { delay: 2.into(), }, ) - .execute_returns([0u8; 32].into()); + .execute_returns(U256::zero()); System::set_block_number(21); // purge expired request PrecompilesValue::get() @@ -804,7 +787,7 @@ fn purge_expired_request_works() { request_id: 0.into(), }, ) - .execute_returns(vec![]); + .execute_returns(()); assert_event_emitted!(RuntimeEvent::Randomness( RandomnessEvent::RequestExpirationExecuted { id: 0 } )); diff --git a/precompiles/referenda/src/lib.rs b/precompiles/referenda/src/lib.rs index 1121c80d43..3080737ed7 100644 --- a/precompiles/referenda/src/lib.rs +++ b/precompiles/referenda/src/lib.rs @@ -27,7 +27,7 @@ use pallet_referenda::{ ReferendumInfo, ReferendumInfoFor, TracksInfo, }; use parity_scale_codec::Encode; -use precompile_utils::{data::String, prelude::*}; +use precompile_utils::prelude::*; use sp_core::{H160, H256, U256}; use sp_std::{boxed::Box, marker::PhantomData, str::FromStr, vec::Vec}; @@ -65,7 +65,7 @@ pub(crate) const SELECTOR_LOG_DECISION_DEPOSIT_REFUNDED: [u8; 32] = pub(crate) const SELECTOR_LOG_SUBMISSION_DEPOSIT_REFUNDED: [u8; 32] = keccak256!("SubmissionDepositRefunded(uint32,address,uint256)"); -#[derive(EvmData)] +#[derive(solidity::Codec)] pub struct TrackInfo { name: UnboundedBytes, max_deciding: U256, @@ -78,7 +78,7 @@ pub struct TrackInfo { min_support: UnboundedBytes, } -#[derive(EvmData)] +#[derive(solidity::Codec)] pub struct OngoingReferendumInfo { /// The track of this referendum. track_id: u16, @@ -116,7 +116,7 @@ pub struct OngoingReferendumInfo { alarm_task_address: UnboundedBytes, } -#[derive(EvmData)] +#[derive(solidity::Codec)] pub struct ClosedReferendumInfo { status: u8, end: U256, @@ -498,10 +498,7 @@ where handle.context().address, SELECTOR_LOG_SUBMITTED_AT, H256::from_low_u64_be(track_id as u64), - EvmDataWriter::new() - .write::(referendum_index) - .write::(proposal_hash) - .build(), + solidity::encode_event_data((referendum_index, proposal_hash)), ); event.record(handle)?; @@ -539,10 +536,7 @@ where handle.context().address, SELECTOR_LOG_SUBMITTED_AFTER, H256::from_low_u64_be(track_id as u64), - EvmDataWriter::new() - .write::(referendum_index) - .write::(proposal_hash) - .build(), + solidity::encode_event_data((referendum_index, proposal_hash)), ); event.record(handle)?; @@ -579,11 +573,11 @@ where let event = log1( handle.context().address, SELECTOR_LOG_DECISION_DEPOSIT_PLACED, - EvmDataWriter::new() - .write::(index) - .write::
(Address(handle.context().caller)) - .write::(decision_deposit) - .build(), + solidity::encode_event_data(( + index, + Address(handle.context().caller), + decision_deposit, + )), ); event.record(handle)?; @@ -619,11 +613,7 @@ where let event = log1( handle.context().address, SELECTOR_LOG_DECISION_DEPOSIT_REFUNDED, - EvmDataWriter::new() - .write::(index) - .write::
(Address(who)) - .write::(refunded_deposit) - .build(), + solidity::encode_event_data((index, Address(who), refunded_deposit)), ); event.record(handle)?; @@ -658,11 +648,7 @@ where let event = log1( handle.context().address, SELECTOR_LOG_SUBMISSION_DEPOSIT_REFUNDED, - EvmDataWriter::new() - .write::(index) - .write::
(Address(who)) - .write::(refunded_deposit) - .build(), + solidity::encode_event_data((index, Address(who), refunded_deposit)), ); event.record(handle)?; diff --git a/precompiles/referenda/src/tests.rs b/precompiles/referenda/src/tests.rs index 23b5d6bf2f..89cb5bc76b 100644 --- a/precompiles/referenda/src/tests.rs +++ b/precompiles/referenda/src/tests.rs @@ -18,7 +18,7 @@ use crate::{ SELECTOR_LOG_SUBMISSION_DEPOSIT_REFUNDED, SELECTOR_LOG_SUBMITTED_AFTER, SELECTOR_LOG_SUBMITTED_AT, }; -use precompile_utils::{prelude::*, testing::*, EvmDataWriter}; +use precompile_utils::{prelude::*, testing::*}; use frame_support::{assert_ok, dispatch::Dispatchable}; use pallet_evm::{Call as EvmCall, Event as EvmEvent}; @@ -42,27 +42,7 @@ fn evm_call(input: Vec) -> EvmCall { #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { - for file in ["Referenda.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCall::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces(&["Referenda.sol"], PCall::supports_selector) } #[test] @@ -100,11 +80,10 @@ fn submitted_at_logs_work() { Precompile1, SELECTOR_LOG_SUBMITTED_AT, H256::from_low_u64_be(0u64), - EvmDataWriter::new() - // Referendum index 0 - .write::(0u32) - .write::(proposal_hash) - .build(), + solidity::encode_event_data(( + 0u32, // referendum index + proposal_hash + )) ), } .into(), @@ -113,11 +92,10 @@ fn submitted_at_logs_work() { Precompile1, SELECTOR_LOG_SUBMITTED_AT, H256::from_low_u64_be(0u64), - EvmDataWriter::new() - // Referendum index 1 - .write::(1u32) - .write::(proposal_hash) - .build(), + solidity::encode_event_data(( + 1u32, // referendum index + proposal_hash + )) ), } .into() @@ -162,11 +140,10 @@ fn submitted_after_logs_work() { Precompile1, SELECTOR_LOG_SUBMITTED_AFTER, H256::from_low_u64_be(0u64), - EvmDataWriter::new() - // Referendum index 0 - .write::(0u32) - .write::(proposal_hash) - .build(), + solidity::encode_event_data(( + 0u32, // referendum index + proposal_hash + )) ), } .into(), @@ -175,11 +152,10 @@ fn submitted_after_logs_work() { Precompile1, SELECTOR_LOG_SUBMITTED_AFTER, H256::from_low_u64_be(0u64), - EvmDataWriter::new() - // Referendum index 1 - .write::(1u32) - .write::(proposal_hash) - .build(), + solidity::encode_event_data(( + 1u32, // referendum index + proposal_hash + )) ), } .into() @@ -227,12 +203,11 @@ fn place_and_refund_decision_deposit_logs_work() { log: log1( Precompile1, SELECTOR_LOG_DECISION_DEPOSIT_PLACED, - EvmDataWriter::new() - .write::(referendum_index) - .write::
(Address(Alice.into())) - // Decision deposit - .write::(U256::from(10)) - .build(), + solidity::encode_event_data(( + referendum_index, + Address(Alice.into()), + U256::from(10), // decision deposit + )) ) } .into() @@ -279,12 +254,11 @@ fn place_and_refund_decision_deposit_logs_work() { log: log1( Precompile1, SELECTOR_LOG_DECISION_DEPOSIT_REFUNDED, - EvmDataWriter::new() - .write::(referendum_index) - .write::
(Address(Alice.into())) - // Decision deposit - .write::(U256::from(10)) - .build(), + solidity::encode_event_data(( + referendum_index, + Address(Alice.into()), + U256::from(10), // decision deposit + )) ) } .into(), @@ -292,12 +266,11 @@ fn place_and_refund_decision_deposit_logs_work() { log: log1( Precompile1, SELECTOR_LOG_SUBMISSION_DEPOSIT_REFUNDED, - EvmDataWriter::new() - .write::(referendum_index) - .write::
(Address(Alice.into())) - // Submission deposit - .write::(U256::from(15)) - .build(), + solidity::encode_event_data(( + referendum_index, + Address(Alice.into()), + U256::from(15), // submission deposit + )) ) } .into() diff --git a/precompiles/relay-encoder/src/lib.rs b/precompiles/relay-encoder/src/lib.rs index 59c666f27c..e53b8b65be 100644 --- a/precompiles/relay-encoder/src/lib.rs +++ b/precompiles/relay-encoder/src/lib.rs @@ -27,7 +27,7 @@ use frame_support::{ traits::ConstU32, }; use pallet_staking::RewardDestination; -use precompile_utils::{data::String, prelude::*}; +use precompile_utils::prelude::*; use sp_core::{H256, U256}; use sp_runtime::AccountId32; use sp_runtime::Perbill; @@ -161,7 +161,7 @@ where #[precompile::view] fn encode_validate( handle: &mut impl PrecompileHandle, - comission: SolidityConvert, + comission: Convert, blocked: bool, ) -> EvmResult { handle.record_cost(RuntimeHelper::::db_read_gas_cost())?; @@ -373,7 +373,7 @@ pub fn u256_to_relay_amount(value: U256) -> EvmResult { .map_err(|_| revert("amount is too large for provided balance type")) } -// A wrapper to be able to implement here the EvmData reader +// A wrapper to be able to implement here the solidity::Codec reader #[derive(Clone, Eq, PartialEq)] pub struct RewardDestinationWrapper(RewardDestination); @@ -389,8 +389,8 @@ impl Into> for RewardDestinationWrapper { } } -impl EvmData for RewardDestinationWrapper { - fn read(reader: &mut EvmDataReader) -> MayRevert { +impl solidity::Codec for RewardDestinationWrapper { + fn read(reader: &mut solidity::codec::Reader) -> MayRevert { let reward_destination = reader.read::>()?; let reward_destination_bytes: Vec<_> = reward_destination.into(); ensure!( @@ -398,7 +398,8 @@ impl EvmData for RewardDestinationWrapper { RevertReason::custom("Reward destinations cannot be empty") ); // For simplicity we use an EvmReader here - let mut encoded_reward_destination = EvmDataReader::new(&reward_destination_bytes); + let mut encoded_reward_destination = + solidity::codec::Reader::new(&reward_destination_bytes); // We take the first byte let enum_selector = encoded_reward_destination.read_raw_bytes(1)?; @@ -418,7 +419,7 @@ impl EvmData for RewardDestinationWrapper { } } - fn write(writer: &mut EvmDataWriter, value: Self) { + fn write(writer: &mut solidity::codec::Writer, value: Self) { let mut encoded: Vec = Vec::new(); let encoded_bytes: UnboundedBytes = match value.0 { RewardDestination::Staked => { @@ -444,14 +445,14 @@ impl EvmData for RewardDestinationWrapper { encoded.as_slice().into() } }; - EvmData::write(writer, encoded_bytes); + solidity::Codec::write(writer, encoded_bytes); } fn has_static_size() -> bool { false } - fn solidity_type() -> String { - UnboundedBytes::solidity_type() + fn signature() -> String { + UnboundedBytes::signature() } } diff --git a/precompiles/relay-encoder/src/tests.rs b/precompiles/relay-encoder/src/tests.rs index 157c5a02d3..ee769392d6 100644 --- a/precompiles/relay-encoder/src/tests.rs +++ b/precompiles/relay-encoder/src/tests.rs @@ -97,18 +97,14 @@ fn test_encode_bond() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(UnboundedBytes::from( - TestEncoder::encode_call(AvailableStakeCalls::Bond( - [1u8; 32].into(), - 100u32.into(), - RewardDestination::Controller, - )) - .as_slice(), - )) - .build(), - ); + .execute_returns(UnboundedBytes::from( + TestEncoder::encode_call(AvailableStakeCalls::Bond( + [1u8; 32].into(), + 100u32.into(), + RewardDestination::Controller, + )) + .as_slice(), + )); }); } @@ -126,14 +122,10 @@ fn test_encode_bond_more() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(UnboundedBytes::from( - TestEncoder::encode_call(AvailableStakeCalls::BondExtra(100u32.into())) - .as_slice(), - )) - .build(), - ); + .execute_returns(UnboundedBytes::from( + TestEncoder::encode_call(AvailableStakeCalls::BondExtra(100u32.into())) + .as_slice(), + )); }); } @@ -147,13 +139,9 @@ fn test_encode_chill() { .prepare_test(Alice, Precompile1, PCall::encode_chill {}) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(UnboundedBytes::from( - TestEncoder::encode_call(AvailableStakeCalls::Chill).as_slice(), - )) - .build(), - ); + .execute_returns(UnboundedBytes::from( + TestEncoder::encode_call(AvailableStakeCalls::Chill).as_slice(), + )); }); } @@ -173,17 +161,13 @@ fn test_encode_nominate() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(UnboundedBytes::from( - TestEncoder::encode_call(AvailableStakeCalls::Nominate(vec![ - [1u8; 32].into(), - [2u8; 32].into(), - ])) - .as_slice(), - )) - .build(), - ); + .execute_returns(UnboundedBytes::from( + TestEncoder::encode_call(AvailableStakeCalls::Nominate(vec![ + [1u8; 32].into(), + [2u8; 32].into(), + ])) + .as_slice(), + )); }); } @@ -201,14 +185,9 @@ fn test_encode_rebond() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(UnboundedBytes::from( - TestEncoder::encode_call(AvailableStakeCalls::Rebond(100u128)) - .as_slice(), - )) - .build(), - ); + .execute_returns(UnboundedBytes::from( + TestEncoder::encode_call(AvailableStakeCalls::Rebond(100u128)).as_slice(), + )); }); } @@ -228,16 +207,10 @@ fn test_encode_set_controller() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(UnboundedBytes::from( - TestEncoder::encode_call(AvailableStakeCalls::SetController( - [1u8; 32].into(), - )) - .as_slice(), - )) - .build(), - ) + .execute_returns(UnboundedBytes::from( + TestEncoder::encode_call(AvailableStakeCalls::SetController([1u8; 32].into())) + .as_slice(), + )) }); } @@ -257,16 +230,12 @@ fn test_encode_set_payee() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(UnboundedBytes::from( - TestEncoder::encode_call(AvailableStakeCalls::SetPayee( - RewardDestination::Controller, - )) - .as_slice(), - )) - .build(), - ); + .execute_returns(UnboundedBytes::from( + TestEncoder::encode_call(AvailableStakeCalls::SetPayee( + RewardDestination::Controller, + )) + .as_slice(), + )); }); } @@ -284,14 +253,9 @@ fn test_encode_unbond() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(UnboundedBytes::from( - TestEncoder::encode_call(AvailableStakeCalls::Unbond(100u32.into())) - .as_slice(), - )) - .build(), - ); + .execute_returns(UnboundedBytes::from( + TestEncoder::encode_call(AvailableStakeCalls::Unbond(100u32.into())).as_slice(), + )); }); } @@ -312,19 +276,13 @@ fn test_encode_validate() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(UnboundedBytes::from( - TestEncoder::encode_call(AvailableStakeCalls::Validate( - ValidatorPrefs { - commission: Perbill::from_parts(100u32.into()), - blocked: true, - }, - )) - .as_slice(), - )) - .build(), - ); + .execute_returns(UnboundedBytes::from( + TestEncoder::encode_call(AvailableStakeCalls::Validate(ValidatorPrefs { + commission: Perbill::from_parts(100u32.into()), + blocked: true, + })) + .as_slice(), + )); }); } @@ -342,42 +300,16 @@ fn test_encode_withdraw_unbonded() { ) .expect_cost(0) // TODO: Test db read/write costs .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(UnboundedBytes::from( - TestEncoder::encode_call(AvailableStakeCalls::WithdrawUnbonded( - 100u32.into(), - )) - .as_slice(), - )) - .build(), - ); + .execute_returns(UnboundedBytes::from( + TestEncoder::encode_call(AvailableStakeCalls::WithdrawUnbonded(100u32.into())) + .as_slice(), + )); }); } #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { - for file in ["RelayEncoder.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCall::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces(&["RelayEncoder.sol"], PCall::supports_selector) } #[test] @@ -394,7 +326,7 @@ fn test_deprecated_solidity_selectors_are_supported() { "encode_set_controller(uint256)", "encode_rebond(uint256)", ] { - let selector = solidity::compute_selector(deprecated_function); + let selector = compute_selector(deprecated_function); if !PCall::supports_selector(selector) { panic!( "failed decoding selector 0x{:x} => '{}' as Action", diff --git a/precompiles/utils/Cargo.toml b/precompiles/utils/Cargo.toml index 8503d2c9b4..4a2550dbdf 100644 --- a/precompiles/utils/Cargo.toml +++ b/precompiles/utils/Cargo.toml @@ -37,10 +37,11 @@ fp-evm = { workspace = true } pallet-evm = { workspace = true, features = [ "forbid-evm-reentrancy" ] } # Polkadot / XCM -xcm = { workspace = true } +xcm = { workspace = true, optional = true } [dev-dependencies] hex-literal = { workspace = true } +xcm = { workspace = true } [features] default = [ "std" ] @@ -55,4 +56,5 @@ std = [ "sp-io/std", "sp-std/std", ] +codec-xcm = [ "xcm" ] testing = [ "derive_more", "hex-literal", "scale-info", "serde", "similar-asserts", "std" ] diff --git a/precompiles/utils/macro/docs/precompile_macro.md b/precompiles/utils/macro/docs/precompile_macro.md index 0ff7ec207f..e72a4e002a 100644 --- a/precompiles/utils/macro/docs/precompile_macro.md +++ b/precompiles/utils/macro/docs/precompile_macro.md @@ -4,7 +4,7 @@ This procedural macro allows to simplify the implementation of an EVM precompile using an `impl` block with annotations to automatically generate: - the implementation of the trait `Precompile` or `PrecompileSet` (exposed by the `fp_evm` crate) -- parsing of the method parameters from Solidity encoding into Rust type, based on the `EvmData` +- parsing of the method parameters from Solidity encoding into Rust type, based on the `solidity::Codec` trait (exposed by the `precompile-utils` crate) - a test to ensure the types expressed in the Solidity signature match the Rust types in the implementation. @@ -60,11 +60,11 @@ support renamed functions with backward compatibility, however the arguments mus type. It is not allowed to use the exact same signature multiple times. The function must take a `&mut impl PrecompileHandle` as parameter, followed by all the parameters -of the Solidity function in the same order. Those parameters types must implement `EvmData`, and +of the Solidity function in the same order. Those parameters types must implement `solidity::Codec`, and their name should match the one used in the Solidity interface (.sol) while being in `snake_case`, which will automatically be converted to `camelCase` in revert messages. The function must return an `EvmResult`, which is an alias of `Result`. This `T` must implement the -`EvmData` trait and must match the return type in the Solidity interface. The macro will +`solidity::Codec` trait and must match the return type in the Solidity interface. The macro will automatically encode it to Solidity format. By default those functions are considered non-payable and non-view (can cause state changes). This @@ -133,7 +133,7 @@ where ## Solidity signatures test The macro will automatically generate a unit test to ensure that the types expressed in a `public` -attribute matches the Rust parameters of the function, thanks to the `EvmData` trait having the +attribute matches the Rust parameters of the function, thanks to the `solidity::Codec` trait having the `solidity_type() -> String` function. If any **parsed** argument (discriminant is not concerned) depends on the type parameters of the diff --git a/precompiles/utils/macro/src/derive_evm_data.rs b/precompiles/utils/macro/src/derive_codec.rs similarity index 76% rename from precompiles/utils/macro/src/derive_evm_data.rs rename to precompiles/utils/macro/src/derive_codec.rs index 75b097dddf..e988e380dc 100644 --- a/precompiles/utils/macro/src/derive_evm_data.rs +++ b/precompiles/utils/macro/src/derive_codec.rs @@ -32,7 +32,7 @@ pub fn main(input: TokenStream) -> TokenStream { let syn::Data::Struct (syn::DataStruct {fields: syn::Fields::Named(fields), ..}) = data else { return quote_spanned! { ident.span() => - compile_error!("EvmData can only be derived for structs with named fields"); + compile_error!("Codec can only be derived for structs with named fields"); } .into() }; @@ -40,14 +40,14 @@ pub fn main(input: TokenStream) -> TokenStream { if fields.len() == 0 { return quote_spanned! { ident.span() => - compile_error!("EvmData can only be derived for structs with at least one field"); + compile_error!("Codec can only be derived for structs with at least one field"); } .into(); } if let Some(unamed_field) = fields.iter().find(|f| f.ident.is_none()) { return quote_spanned! { unamed_field.ty.span() => - compile_error!("EvmData can only be derived for structs with named fields"); + compile_error!("Codec can only be derived for structs with named fields"); } .into(); } @@ -65,8 +65,8 @@ pub fn main(input: TokenStream) -> TokenStream { let evm_data_trait_path = { let mut segments = Punctuated::::new(); segments.push(Ident::new("precompile_utils", Span::call_site()).into()); - segments.push(Ident::new("data", Span::call_site()).into()); - segments.push(Ident::new("EvmData", Span::call_site()).into()); + segments.push(Ident::new("solidity", Span::call_site()).into()); + segments.push(Ident::new("Codec", Span::call_site()).into()); Path { leading_colon: Some(Default::default()), segments, @@ -99,12 +99,12 @@ pub fn main(input: TokenStream) -> TokenStream { let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); quote! { - impl #impl_generics ::precompile_utils::data::EvmData for #ident #ty_generics + impl #impl_generics ::precompile_utils::solidity::codec::Codec for #ident #ty_generics #where_clause { fn read( - reader: &mut ::precompile_utils::data::EvmDataReader - ) -> ::precompile_utils::revert::MayRevert { - use ::precompile_utils::revert::BacktraceExt as _; + reader: &mut ::precompile_utils::solidity::codec::Reader + ) -> ::precompile_utils::solidity::revert::MayRevert { + use ::precompile_utils::solidity::revert::BacktraceExt as _; let (#(#fields_ident,)*): (#(#fields_ty,)*) = reader .read() .map_in_tuple_to_field(&[#(#fields_name_lit),*])?; @@ -113,16 +113,16 @@ pub fn main(input: TokenStream) -> TokenStream { }) } - fn write(writer: &mut ::precompile_utils::data::EvmDataWriter, value: Self) { - ::precompile_utils::data::EvmData::write(writer, (#(value.#fields_ident,)*)); + fn write(writer: &mut ::precompile_utils::solidity::codec::Writer, value: Self) { + ::precompile_utils::solidity::codec::Codec::write(writer, (#(value.#fields_ident,)*)); } fn has_static_size() -> bool { <(#(#fields_ty,)*)>::has_static_size() } - fn solidity_type() -> String { - <(#(#fields_ty,)*)>::solidity_type() + fn signature() -> String { + <(#(#fields_ty,)*)>::signature() } } } diff --git a/precompiles/utils/macro/src/lib.rs b/precompiles/utils/macro/src/lib.rs index 5ed758a9a3..9214482837 100644 --- a/precompiles/utils/macro/src/lib.rs +++ b/precompiles/utils/macro/src/lib.rs @@ -18,16 +18,11 @@ extern crate proc_macro; use proc_macro::TokenStream; -use proc_macro2::Literal; use quote::{quote, quote_spanned}; use sha3::{Digest, Keccak256}; -use syn::{ - parse_macro_input, spanned::Spanned, Attribute, Expr, ExprLit, Ident, ItemEnum, ItemType, Lit, - LitStr, -}; +use syn::{parse_macro_input, spanned::Spanned, Expr, Ident, ItemType, Lit, LitStr}; -mod derive_evm_data; -mod generate_function_selector; +mod derive_codec; mod precompile; mod precompile_name_from_address; @@ -65,35 +60,6 @@ pub fn keccak256(input: TokenStream) -> TokenStream { quote!(#eval_ts).into() } -/// This macro allows to associate to each variant of an enumeration a discriminant (of type u32 -/// whose value corresponds to the first 4 bytes of the Hash Keccak256 of the character string -///indicated by the user of this macro. -/// -/// Usage: -/// -/// ```ignore -/// #[generate_function_selector] -/// enum Action { -/// Toto = "toto()", -/// Tata = "tata()", -/// } -/// ``` -/// -/// Extended to: -/// -/// ```rust -/// #[repr(u32)] -/// enum Action { -/// Toto = 119097542u32, -/// Tata = 1414311903u32, -/// } -/// ``` -/// -#[proc_macro_attribute] -pub fn generate_function_selector(attr: TokenStream, input: TokenStream) -> TokenStream { - generate_function_selector::main(attr, input) -} - #[proc_macro_attribute] pub fn precompile(attr: TokenStream, input: TokenStream) -> TokenStream { precompile::main(attr, input) @@ -104,7 +70,7 @@ pub fn precompile_name_from_address(attr: TokenStream, input: TokenStream) -> To precompile_name_from_address::main(attr, input) } -#[proc_macro_derive(EvmData)] -pub fn derive_evm_data(input: TokenStream) -> TokenStream { - derive_evm_data::main(input) +#[proc_macro_derive(Codec)] +pub fn derive_codec(input: TokenStream) -> TokenStream { + derive_codec::main(input) } diff --git a/precompiles/utils/macro/src/precompile/expand.rs b/precompiles/utils/macro/src/precompile/expand.rs index 07c2926829..c5fd36ffaf 100644 --- a/precompiles/utils/macro/src/precompile/expand.rs +++ b/precompiles/utils/macro/src/precompile/expand.rs @@ -90,8 +90,8 @@ impl Precompile { let modifier = syn::Ident::new(modifier, span); quote!( - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::#modifier)?; ) }); @@ -108,7 +108,7 @@ impl Precompile { fn #fn_parse( handle: &mut impl PrecompileHandle ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; + use ::precompile_utils::solidity::revert::InjectBacktrace; #modifier_check #variant_parsing @@ -118,7 +118,7 @@ impl Precompile { } /// Generates the parsing code for a variant, reading the input from the handle and - /// parsing it using EvmDataReader. + /// parsing it using Reader. fn expand_variant_parsing_from_handle( variant_ident: &syn::Ident, variant: &Variant, @@ -218,7 +218,7 @@ impl Precompile { )* pub fn encode(self) -> ::sp_std::vec::Vec { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::Writer; match self { #( Self::#variants_ident2 { #(#variants_list),* } => { @@ -271,11 +271,11 @@ impl Precompile { .map(|_| quote!(discriminant,)); let write_output = quote_spanned!(output_span=> - ::precompile_utils::data::encode_as_function_return_value(output?) + ::precompile_utils::solidity::encode_return_value(output?) ); quote!( - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity; let output = <#impl_type>::#variant_ident( #opt_discriminant_arg handle, @@ -291,7 +291,7 @@ impl Precompile { #opt_discriminant_arg handle: &mut impl PrecompileHandle ) -> ::precompile_utils::EvmResult<::fp_evm::PrecompileOutput> { - use ::precompile_utils::data::EvmDataWriter; + use ::precompile_utils::solidity::codec::Writer; use ::fp_evm::{PrecompileOutput, ExitSucceed}; let output = match self { @@ -322,7 +322,7 @@ impl Precompile { }); quote!( - EvmDataWriter::new_with_selector(#selector) + Writer::new_with_selector(#selector) #(#write_arguments)* .build() ) @@ -357,7 +357,7 @@ impl Precompile { pub fn parse_call_data( handle: &mut impl PrecompileHandle ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::RevertReason; + use ::precompile_utils::solidity::revert::RevertReason; let input = handle.input(); @@ -463,7 +463,7 @@ impl Precompile { quote_spanned!(span=> assert_eq!( #solidity, - <(#(#types,)*) as EvmData>::solidity_type(), + <(#(#types,)*) as Codec>::signature(), "{} function signature doesn't match (left: attribute, right: computed \ from Rust types)", #name @@ -481,7 +481,7 @@ impl Precompile { quote!( #[allow(non_snake_case)] pub(crate) fn #inner_name #impl_generics () #where_clause { - use ::precompile_utils::data::EvmData; + use ::precompile_utils::solidity::Codec; #(#variant_test)* } @@ -496,7 +496,7 @@ impl Precompile { quote!( #[allow(non_snake_case)] pub(crate) fn #inner_name() { - use ::precompile_utils::data::EvmData; + use ::precompile_utils::solidity::Codec; #(#variant_test)* } diff --git a/precompiles/utils/macro/src/precompile/mod.rs b/precompiles/utils/macro/src/precompile/mod.rs index cbc432d06f..4cd63ed287 100644 --- a/precompiles/utils/macro/src/precompile/mod.rs +++ b/precompiles/utils/macro/src/precompile/mod.rs @@ -106,7 +106,7 @@ struct Variant { /// A unit test will be generated to check that this selector matches /// the Rust arguments. /// - /// > EvmData trait allows to generate this string at runtime only. Thus + /// > solidity::Codec trait allows to generate this string at runtime only. Thus /// > it is required to write it manually in the selector attribute, and /// > a unit test is generated to check it matches. solidity_arguments_type: String, diff --git a/precompiles/utils/macro/tests/compile-fail/derive_evm_data/empty_struct.rs b/precompiles/utils/macro/tests/compile-fail/derive_codec/empty_struct.rs similarity index 90% rename from precompiles/utils/macro/tests/compile-fail/derive_evm_data/empty_struct.rs rename to precompiles/utils/macro/tests/compile-fail/derive_codec/empty_struct.rs index 548c66bd2d..ea2cd4621a 100644 --- a/precompiles/utils/macro/tests/compile-fail/derive_evm_data/empty_struct.rs +++ b/precompiles/utils/macro/tests/compile-fail/derive_codec/empty_struct.rs @@ -16,13 +16,13 @@ use precompile_utils::prelude::*; -#[derive(EvmData)] +#[derive(solidity::Codec)] struct Empty1; -#[derive(EvmData)] +#[derive(solidity::Codec)] struct Empty2 {} -#[derive(EvmData)] +#[derive(solidity::Codec)] struct Empty3 (); fn main() {} \ No newline at end of file diff --git a/precompiles/utils/macro/tests/compile-fail/derive_codec/empty_struct.stderr b/precompiles/utils/macro/tests/compile-fail/derive_codec/empty_struct.stderr new file mode 100644 index 0000000000..8c0a9d8bae --- /dev/null +++ b/precompiles/utils/macro/tests/compile-fail/derive_codec/empty_struct.stderr @@ -0,0 +1,17 @@ +error: Codec can only be derived for structs with named fields + --> tests/compile-fail/derive_codec/empty_struct.rs:20:8 + | +20 | struct Empty1; + | ^^^^^^ + +error: Codec can only be derived for structs with at least one field + --> tests/compile-fail/derive_codec/empty_struct.rs:23:8 + | +23 | struct Empty2 {} + | ^^^^^^ + +error: Codec can only be derived for structs with named fields + --> tests/compile-fail/derive_codec/empty_struct.rs:26:8 + | +26 | struct Empty3 (); + | ^^^^^^ diff --git a/precompiles/utils/macro/tests/compile-fail/derive_evm_data/enum.rs b/precompiles/utils/macro/tests/compile-fail/derive_codec/enum.rs similarity index 96% rename from precompiles/utils/macro/tests/compile-fail/derive_evm_data/enum.rs rename to precompiles/utils/macro/tests/compile-fail/derive_codec/enum.rs index a1c5f71c38..de0a7a6123 100644 --- a/precompiles/utils/macro/tests/compile-fail/derive_evm_data/enum.rs +++ b/precompiles/utils/macro/tests/compile-fail/derive_codec/enum.rs @@ -16,7 +16,7 @@ use precompile_utils::prelude::*; -#[derive(EvmData)] +#[derive(solidity::Codec)] enum Test { One, Two(u8), diff --git a/precompiles/utils/macro/tests/compile-fail/derive_codec/enum.stderr b/precompiles/utils/macro/tests/compile-fail/derive_codec/enum.stderr new file mode 100644 index 0000000000..42a65d4a17 --- /dev/null +++ b/precompiles/utils/macro/tests/compile-fail/derive_codec/enum.stderr @@ -0,0 +1,5 @@ +error: Codec can only be derived for structs with named fields + --> tests/compile-fail/derive_codec/enum.rs:20:6 + | +20 | enum Test { + | ^^^^ diff --git a/precompiles/utils/macro/tests/compile-fail/derive_evm_data/empty_struct.stderr b/precompiles/utils/macro/tests/compile-fail/derive_evm_data/empty_struct.stderr deleted file mode 100644 index 67e00cb85b..0000000000 --- a/precompiles/utils/macro/tests/compile-fail/derive_evm_data/empty_struct.stderr +++ /dev/null @@ -1,17 +0,0 @@ -error: EvmData can only be derived for structs with named fields - --> tests/compile-fail/derive_evm_data/empty_struct.rs:20:8 - | -20 | struct Empty1; - | ^^^^^^ - -error: EvmData can only be derived for structs with at least one field - --> tests/compile-fail/derive_evm_data/empty_struct.rs:23:8 - | -23 | struct Empty2 {} - | ^^^^^^ - -error: EvmData can only be derived for structs with named fields - --> tests/compile-fail/derive_evm_data/empty_struct.rs:26:8 - | -26 | struct Empty3 (); - | ^^^^^^ diff --git a/precompiles/utils/macro/tests/compile-fail/derive_evm_data/enum.stderr b/precompiles/utils/macro/tests/compile-fail/derive_evm_data/enum.stderr deleted file mode 100644 index af7150ccb7..0000000000 --- a/precompiles/utils/macro/tests/compile-fail/derive_evm_data/enum.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: EvmData can only be derived for structs with named fields - --> tests/compile-fail/derive_evm_data/enum.rs:20:6 - | -20 | enum Test { - | ^^^^ diff --git a/precompiles/utils/macro/tests/compile-fail/precompile/evm-data/arg-dont-impl-evmdata.rs b/precompiles/utils/macro/tests/compile-fail/precompile/codec/arg-dont-impl-codec.rs similarity index 100% rename from precompiles/utils/macro/tests/compile-fail/precompile/evm-data/arg-dont-impl-evmdata.rs rename to precompiles/utils/macro/tests/compile-fail/precompile/codec/arg-dont-impl-codec.rs diff --git a/precompiles/utils/macro/tests/compile-fail/precompile/evm-data/arg-dont-impl-evmdata.stderr b/precompiles/utils/macro/tests/compile-fail/precompile/codec/arg-dont-impl-codec.stderr similarity index 64% rename from precompiles/utils/macro/tests/compile-fail/precompile/evm-data/arg-dont-impl-evmdata.stderr rename to precompiles/utils/macro/tests/compile-fail/precompile/codec/arg-dont-impl-codec.stderr index baac51c9ea..1e87e3c771 100644 --- a/precompiles/utils/macro/tests/compile-fail/precompile/evm-data/arg-dont-impl-evmdata.stderr +++ b/precompiles/utils/macro/tests/compile-fail/precompile/codec/arg-dont-impl-codec.stderr @@ -1,10 +1,10 @@ -error[E0277]: the trait bound `String: EvmData` is not satisfied - --> tests/compile-fail/precompile/evm-data/arg-dont-impl-evmdata.rs:26:43 +error[E0277]: the trait bound `String: Codec` is not satisfied + --> tests/compile-fail/precompile/codec/arg-dont-impl-codec.rs:26:43 | 26 | fn foo(test: &mut impl PrecompileHandle, arg: String) -> EvmResult { - | ^^^ the trait `EvmData` is not implemented for `String` + | ^^^ the trait `Codec` is not implemented for `String` | - = help: the following other types implement trait `EvmData`: + = help: the following other types implement trait `Codec`: () (TupleElement0, TupleElement1) (TupleElement0, TupleElement1, TupleElement2) @@ -14,19 +14,19 @@ error[E0277]: the trait bound `String: EvmData` is not satisfied (TupleElement0, TupleElement1, TupleElement2, TupleElement3, TupleElement4, TupleElement5, TupleElement6) (TupleElement0, TupleElement1, TupleElement2, TupleElement3, TupleElement4, TupleElement5, TupleElement6, TupleElement7) and $N others -note: required by a bound in `EvmDataReader::<'a>::read` - --> $WORKSPACE/precompiles/utils/src/data/mod.rs +note: required by a bound in `Reader::<'inner>::read` + --> $WORKSPACE/precompiles/utils/src/solidity/codec/mod.rs | - | pub fn read(&mut self) -> MayRevert { - | ^^^^^^^ required by this bound in `EvmDataReader::<'a>::read` + | pub fn read(&mut self) -> MayRevert { + | ^^^^^ required by this bound in `Reader::<'inner>::read` -error[E0277]: the trait bound `String: EvmData` is not satisfied - --> tests/compile-fail/precompile/evm-data/arg-dont-impl-evmdata.rs:26:43 +error[E0277]: the trait bound `String: Codec` is not satisfied + --> tests/compile-fail/precompile/codec/arg-dont-impl-codec.rs:26:43 | 26 | fn foo(test: &mut impl PrecompileHandle, arg: String) -> EvmResult { - | ^^^ the trait `EvmData` is not implemented for `String` + | ^^^ the trait `Codec` is not implemented for `String` | - = help: the following other types implement trait `EvmData`: + = help: the following other types implement trait `Codec`: () (TupleElement0, TupleElement1) (TupleElement0, TupleElement1, TupleElement2) @@ -36,19 +36,19 @@ error[E0277]: the trait bound `String: EvmData` is not satisfied (TupleElement0, TupleElement1, TupleElement2, TupleElement3, TupleElement4, TupleElement5, TupleElement6) (TupleElement0, TupleElement1, TupleElement2, TupleElement3, TupleElement4, TupleElement5, TupleElement6, TupleElement7) and $N others -note: required by a bound in `EvmDataWriter::write` - --> $WORKSPACE/precompiles/utils/src/data/mod.rs +note: required by a bound in `precompile_utils::solidity::codec::Writer::write` + --> $WORKSPACE/precompiles/utils/src/solidity/codec/mod.rs | - | pub fn write(mut self, value: T) -> Self { - | ^^^^^^^ required by this bound in `EvmDataWriter::write` + | pub fn write(mut self, value: T) -> Self { + | ^^^^^ required by this bound in `Writer::write` -error[E0277]: the trait bound `String: EvmData` is not satisfied - --> tests/compile-fail/precompile/evm-data/arg-dont-impl-evmdata.rs:26:5 +error[E0277]: the trait bound `String: Codec` is not satisfied + --> tests/compile-fail/precompile/codec/arg-dont-impl-codec.rs:26:5 | 26 | fn foo(test: &mut impl PrecompileHandle, arg: String) -> EvmResult { - | ^^^ the trait `EvmData` is not implemented for `String` + | ^^^ the trait `Codec` is not implemented for `String` | - = help: the following other types implement trait `EvmData`: + = help: the following other types implement trait `Codec`: () (TupleElement0, TupleElement1) (TupleElement0, TupleElement1, TupleElement2) @@ -58,4 +58,4 @@ error[E0277]: the trait bound `String: EvmData` is not satisfied (TupleElement0, TupleElement1, TupleElement2, TupleElement3, TupleElement4, TupleElement5, TupleElement6) (TupleElement0, TupleElement1, TupleElement2, TupleElement3, TupleElement4, TupleElement5, TupleElement6, TupleElement7) and $N others - = note: required for `(String,)` to implement `EvmData` + = note: required for `(String,)` to implement `Codec` diff --git a/precompiles/utils/macro/tests/compile-fail/precompile/evm-data/no-output.rs b/precompiles/utils/macro/tests/compile-fail/precompile/codec/no-output.rs similarity index 100% rename from precompiles/utils/macro/tests/compile-fail/precompile/evm-data/no-output.rs rename to precompiles/utils/macro/tests/compile-fail/precompile/codec/no-output.rs diff --git a/precompiles/utils/macro/tests/compile-fail/precompile/evm-data/no-output.stderr b/precompiles/utils/macro/tests/compile-fail/precompile/codec/no-output.stderr similarity index 72% rename from precompiles/utils/macro/tests/compile-fail/precompile/evm-data/no-output.stderr rename to precompiles/utils/macro/tests/compile-fail/precompile/codec/no-output.stderr index aef1b5e539..7a2758d0f5 100644 --- a/precompiles/utils/macro/tests/compile-fail/precompile/evm-data/no-output.stderr +++ b/precompiles/utils/macro/tests/compile-fail/precompile/codec/no-output.stderr @@ -1,5 +1,5 @@ error: A precompile method must have a return type of `EvmResult<_>` (exposed by `precompile_utils`) - --> tests/compile-fail/precompile/evm-data/no-output.rs:24:2 + --> tests/compile-fail/precompile/codec/no-output.rs:24:2 | 24 | fn foo(test: &mut impl PrecompileHandle) { | ^^ diff --git a/precompiles/utils/macro/tests/compile-fail/precompile/evm-data/output-dont-impl-evmdata.rs b/precompiles/utils/macro/tests/compile-fail/precompile/codec/output-dont-impl-codec.rs similarity index 100% rename from precompiles/utils/macro/tests/compile-fail/precompile/evm-data/output-dont-impl-evmdata.rs rename to precompiles/utils/macro/tests/compile-fail/precompile/codec/output-dont-impl-codec.rs diff --git a/precompiles/utils/macro/tests/compile-fail/precompile/evm-data/output-dont-impl-evmdata.stderr b/precompiles/utils/macro/tests/compile-fail/precompile/codec/output-dont-impl-codec.stderr similarity index 59% rename from precompiles/utils/macro/tests/compile-fail/precompile/evm-data/output-dont-impl-evmdata.stderr rename to precompiles/utils/macro/tests/compile-fail/precompile/codec/output-dont-impl-codec.stderr index ded0b8191a..52ba67e654 100644 --- a/precompiles/utils/macro/tests/compile-fail/precompile/evm-data/output-dont-impl-evmdata.stderr +++ b/precompiles/utils/macro/tests/compile-fail/precompile/codec/output-dont-impl-codec.stderr @@ -1,10 +1,10 @@ -error[E0277]: the trait bound `String: EvmData` is not satisfied - --> tests/compile-fail/precompile/evm-data/output-dont-impl-evmdata.rs:26:46 +error[E0277]: the trait bound `String: Codec` is not satisfied + --> tests/compile-fail/precompile/codec/output-dont-impl-codec.rs:26:46 | 26 | fn foo(test: &mut impl PrecompileHandle) -> EvmResult { - | ^^^^^^^^^ the trait `EvmData` is not implemented for `String` + | ^^^^^^^^^ the trait `Codec` is not implemented for `String` | - = help: the following other types implement trait `EvmData`: + = help: the following other types implement trait `Codec`: () (TupleElement0, TupleElement1) (TupleElement0, TupleElement1, TupleElement2) @@ -14,8 +14,8 @@ error[E0277]: the trait bound `String: EvmData` is not satisfied (TupleElement0, TupleElement1, TupleElement2, TupleElement3, TupleElement4, TupleElement5, TupleElement6) (TupleElement0, TupleElement1, TupleElement2, TupleElement3, TupleElement4, TupleElement5, TupleElement6, TupleElement7) and $N others -note: required by a bound in `encode_as_function_return_value` - --> $WORKSPACE/precompiles/utils/src/data/mod.rs +note: required by a bound in `encode_arguments` + --> $WORKSPACE/precompiles/utils/src/solidity/codec/mod.rs | - | pub fn encode_as_function_return_value(value: T) -> Vec { - | ^^^^^^^ required by this bound in `encode_as_function_return_value` + | pub fn encode_arguments(value: T) -> Vec { + | ^^^^^ required by this bound in `encode_arguments` diff --git a/precompiles/utils/macro/tests/compile-fail/precompile/evm-data/output-not-result.rs b/precompiles/utils/macro/tests/compile-fail/precompile/codec/output-not-result.rs similarity index 100% rename from precompiles/utils/macro/tests/compile-fail/precompile/evm-data/output-not-result.rs rename to precompiles/utils/macro/tests/compile-fail/precompile/codec/output-not-result.rs diff --git a/precompiles/utils/macro/tests/compile-fail/precompile/evm-data/output-not-result.stderr b/precompiles/utils/macro/tests/compile-fail/precompile/codec/output-not-result.stderr similarity index 81% rename from precompiles/utils/macro/tests/compile-fail/precompile/evm-data/output-not-result.stderr rename to precompiles/utils/macro/tests/compile-fail/precompile/codec/output-not-result.stderr index 276545c3ee..c104ae8fb3 100644 --- a/precompiles/utils/macro/tests/compile-fail/precompile/evm-data/output-not-result.stderr +++ b/precompiles/utils/macro/tests/compile-fail/precompile/codec/output-not-result.stderr @@ -1,5 +1,5 @@ error[E0277]: the `?` operator can only be applied to values that implement `Try` - --> tests/compile-fail/precompile/evm-data/output-not-result.rs:25:46 + --> tests/compile-fail/precompile/codec/output-not-result.rs:25:46 | 25 | fn foo(test: &mut impl PrecompileHandle) -> String { | ^^^^^^ the `?` operator cannot be applied to type `String` diff --git a/precompiles/utils/macro/tests/compile-fail/precompile/evm-data/output-wrong-error-result.rs b/precompiles/utils/macro/tests/compile-fail/precompile/codec/output-wrong-error-result.rs similarity index 100% rename from precompiles/utils/macro/tests/compile-fail/precompile/evm-data/output-wrong-error-result.rs rename to precompiles/utils/macro/tests/compile-fail/precompile/codec/output-wrong-error-result.rs diff --git a/precompiles/utils/macro/tests/compile-fail/precompile/evm-data/output-wrong-error-result.stderr b/precompiles/utils/macro/tests/compile-fail/precompile/codec/output-wrong-error-result.stderr similarity index 82% rename from precompiles/utils/macro/tests/compile-fail/precompile/evm-data/output-wrong-error-result.stderr rename to precompiles/utils/macro/tests/compile-fail/precompile/codec/output-wrong-error-result.stderr index a640808e73..fa1fc8f71c 100644 --- a/precompiles/utils/macro/tests/compile-fail/precompile/evm-data/output-wrong-error-result.stderr +++ b/precompiles/utils/macro/tests/compile-fail/precompile/codec/output-wrong-error-result.stderr @@ -1,5 +1,5 @@ error[E0277]: `?` couldn't convert the error to `PrecompileFailure` - --> tests/compile-fail/precompile/evm-data/output-wrong-error-result.rs:25:51 + --> tests/compile-fail/precompile/codec/output-wrong-error-result.rs:25:51 | 25 | fn foo(test: &mut impl PrecompileHandle) -> Result<(), String> { | ^ the trait `From` is not implemented for `PrecompileFailure` @@ -9,5 +9,5 @@ error[E0277]: `?` couldn't convert the error to `PrecompileFailure` > > > - > + > = note: required for `Result` to implement `FromResidual>` diff --git a/precompiles/utils/macro/tests/expand/precompile.expanded.rs b/precompiles/utils/macro/tests/expand/precompile.expanded.rs index f3973abfa8..560be33532 100644 --- a/precompiles/utils/macro/tests/expand/precompile.expanded.rs +++ b/precompiles/utils/macro/tests/expand/precompile.expanded.rs @@ -90,7 +90,7 @@ where pub fn parse_call_data( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::RevertReason; + use ::precompile_utils::solidity::revert::RevertReason; let input = handle.input(); let selector = input .get(0..4) @@ -109,9 +109,9 @@ where fn _parse_batch_all( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; let mut input = handle.read_after_selector()?; input.expect_arguments(4usize)?; @@ -125,9 +125,9 @@ where fn _parse_batch_some( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; let mut input = handle.read_after_selector()?; input.expect_arguments(4usize)?; @@ -141,9 +141,9 @@ where fn _parse_batch_some_until_failure( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; let mut input = handle.read_after_selector()?; input.expect_arguments(4usize)?; @@ -157,9 +157,9 @@ where fn _parse_fallback( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; Ok(Self::fallback {}) } @@ -167,34 +167,34 @@ where self, handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult<::fp_evm::PrecompileOutput> { - use ::precompile_utils::data::EvmDataWriter; + use ::precompile_utils::solidity::codec::Writer; use ::fp_evm::{PrecompileOutput, ExitSucceed}; let output = match self { Self::batch_all { to, value, call_data, gas_limit } => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::batch_all(handle, to, value, call_data, gas_limit); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::batch_some { to, value, call_data, gas_limit } => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::batch_some(handle, to, value, call_data, gas_limit); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::batch_some_until_failure { to, value, call_data, gas_limit } => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::batch_some_until_failure(handle, to, value, call_data, gas_limit); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::fallback {} => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::fallback(handle); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::__phantom(_, _) => { ::core::panicking::panic_fmt( @@ -231,10 +231,10 @@ where &[] } pub fn encode(self) -> ::sp_std::vec::Vec { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::Writer; match self { Self::batch_all { to, value, call_data, gas_limit } => { - EvmDataWriter::new_with_selector(2531431096u32) + Writer::new_with_selector(2531431096u32) .write(to) .write(value) .write(call_data) @@ -242,7 +242,7 @@ where .build() } Self::batch_some { to, value, call_data, gas_limit } => { - EvmDataWriter::new_with_selector(2044677020u32) + Writer::new_with_selector(2044677020u32) .write(to) .write(value) .write(call_data) @@ -250,7 +250,7 @@ where .build() } Self::batch_some_until_failure { to, value, call_data, gas_limit } => { - EvmDataWriter::new_with_selector(3473183175u32) + Writer::new_with_selector(3473183175u32) .write(to) .write(value) .write(call_data) @@ -287,7 +287,7 @@ where } #[allow(non_snake_case)] pub(crate) fn __BatchPrecompile_test_solidity_signatures_inner() { - use ::precompile_utils::data::EvmData; + use ::precompile_utils::solidity::Codec; match ( &"(address[],uint256[],bytes[],uint64[])", &<( @@ -295,7 +295,7 @@ pub(crate) fn __BatchPrecompile_test_solidity_signatures_inner() { BoundedVec, BoundedVec, GetArrayLimit>, BoundedVec, - ) as EvmData>::solidity_type(), + ) as Codec>::signature(), ) { (left_val, right_val) => { if !(*left_val == *right_val) { @@ -321,7 +321,7 @@ pub(crate) fn __BatchPrecompile_test_solidity_signatures_inner() { BoundedVec, BoundedVec, GetArrayLimit>, BoundedVec, - ) as EvmData>::solidity_type(), + ) as Codec>::signature(), ) { (left_val, right_val) => { if !(*left_val == *right_val) { @@ -347,7 +347,7 @@ pub(crate) fn __BatchPrecompile_test_solidity_signatures_inner() { BoundedVec, BoundedVec, GetArrayLimit>, BoundedVec, - ) as EvmData>::solidity_type(), + ) as Codec>::signature(), ) { (left_val, right_val) => { if !(*left_val == *right_val) { @@ -366,7 +366,7 @@ pub(crate) fn __BatchPrecompile_test_solidity_signatures_inner() { } } }; - match (&"()", &<() as EvmData>::solidity_type()) { + match (&"()", &<() as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; diff --git a/precompiles/utils/macro/tests/expand/precompileset.expanded.rs b/precompiles/utils/macro/tests/expand/precompileset.expanded.rs index 57e1f4f6cc..d1f4b8129e 100644 --- a/precompiles/utils/macro/tests/expand/precompileset.expanded.rs +++ b/precompiles/utils/macro/tests/expand/precompileset.expanded.rs @@ -288,7 +288,7 @@ where pub fn parse_call_data( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::RevertReason; + use ::precompile_utils::solidity::revert::RevertReason; let input = handle.input(); let selector = input .get(0..4) @@ -333,9 +333,9 @@ where fn _parse_allowance( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; let mut input = handle.read_after_selector()?; input.expect_arguments(2usize)?; @@ -347,9 +347,9 @@ where fn _parse_approve( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; let mut input = handle.read_after_selector()?; input.expect_arguments(2usize)?; @@ -361,9 +361,9 @@ where fn _parse_balance_of( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; let mut input = handle.read_after_selector()?; input.expect_arguments(1usize)?; @@ -374,9 +374,9 @@ where fn _parse_burn( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; let mut input = handle.read_after_selector()?; input.expect_arguments(2usize)?; @@ -388,36 +388,36 @@ where fn _parse_clear_metadata( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; Ok(Self::clear_metadata {}) } fn _parse_decimals( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; Ok(Self::decimals {}) } fn _parse_eip2612_domain_separator( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::View)?; Ok(Self::eip2612_domain_separator {}) } fn _parse_eip2612_nonces( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::View)?; let mut input = handle.read_after_selector()?; input.expect_arguments(1usize)?; @@ -428,9 +428,9 @@ where fn _parse_eip2612_permit( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; let mut input = handle.read_after_selector()?; input.expect_arguments(7usize)?; @@ -447,9 +447,9 @@ where fn _parse_freeze( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; let mut input = handle.read_after_selector()?; input.expect_arguments(1usize)?; @@ -460,18 +460,18 @@ where fn _parse_freeze_asset( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; Ok(Self::freeze_asset {}) } fn _parse_mint( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; let mut input = handle.read_after_selector()?; input.expect_arguments(2usize)?; @@ -483,18 +483,18 @@ where fn _parse_name( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; Ok(Self::name {}) } fn _parse_set_metadata( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; let mut input = handle.read_after_selector()?; input.expect_arguments(3usize)?; @@ -507,9 +507,9 @@ where fn _parse_set_team( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; let mut input = handle.read_after_selector()?; input.expect_arguments(3usize)?; @@ -522,18 +522,18 @@ where fn _parse_symbol( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; Ok(Self::symbol {}) } fn _parse_thaw( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; let mut input = handle.read_after_selector()?; input.expect_arguments(1usize)?; @@ -544,27 +544,27 @@ where fn _parse_thaw_asset( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; Ok(Self::thaw_asset {}) } fn _parse_total_supply( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; Ok(Self::total_supply {}) } fn _parse_transfer( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; let mut input = handle.read_after_selector()?; input.expect_arguments(2usize)?; @@ -576,9 +576,9 @@ where fn _parse_transfer_from( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; let mut input = handle.read_after_selector()?; input.expect_arguments(3usize)?; @@ -591,9 +591,9 @@ where fn _parse_transfer_ownership( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; let mut input = handle.read_after_selector()?; input.expect_arguments(1usize)?; @@ -606,65 +606,65 @@ where discriminant: Discriminant, handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult<::fp_evm::PrecompileOutput> { - use ::precompile_utils::data::EvmDataWriter; + use ::precompile_utils::solidity::codec::Writer; use ::fp_evm::{PrecompileOutput, ExitSucceed}; let output = match self { Self::allowance { owner, spender } => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::allowance(discriminant, handle, owner, spender); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::approve { spender, value } => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::approve(discriminant, handle, spender, value); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::balance_of { who } => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::balance_of(discriminant, handle, who); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::burn { from, value } => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::burn(discriminant, handle, from, value); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::clear_metadata {} => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::clear_metadata(discriminant, handle); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::decimals {} => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::decimals(discriminant, handle); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::eip2612_domain_separator {} => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::eip2612_domain_separator(discriminant, handle); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::eip2612_nonces { owner } => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::eip2612_nonces(discriminant, handle, owner); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::eip2612_permit { owner, spender, value, deadline, v, r, s } => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::eip2612_permit( @@ -678,92 +678,92 @@ where r, s, ); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::freeze { account } => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::freeze(discriminant, handle, account); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::freeze_asset {} => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::freeze_asset(discriminant, handle); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::mint { to, value } => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::mint(discriminant, handle, to, value); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::name {} => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::name(discriminant, handle); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::set_metadata { name, symbol, decimals } => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::set_metadata(discriminant, handle, name, symbol, decimals); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::set_team { issuer, admin, freezer } => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::set_team(discriminant, handle, issuer, admin, freezer); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::symbol {} => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::symbol(discriminant, handle); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::thaw { account } => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::thaw(discriminant, handle, account); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::thaw_asset {} => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::thaw_asset(discriminant, handle); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::total_supply {} => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::total_supply(discriminant, handle); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::transfer { to, value } => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::transfer(discriminant, handle, to, value); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::transfer_from { from, to, value } => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::transfer_from(discriminant, handle, from, to, value); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::transfer_ownership { owner } => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = >::transfer_ownership(discriminant, handle, owner); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::__phantom(_, _) => { ::core::panicking::panic_fmt( @@ -908,41 +908,36 @@ where &[4076725131u32, 4030008324u32] } pub fn encode(self) -> ::sp_std::vec::Vec { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::Writer; match self { Self::allowance { owner, spender } => { - EvmDataWriter::new_with_selector(3714247998u32) + Writer::new_with_selector(3714247998u32) .write(owner) .write(spender) .build() } Self::approve { spender, value } => { - EvmDataWriter::new_with_selector(157198259u32) + Writer::new_with_selector(157198259u32) .write(spender) .write(value) .build() } Self::balance_of { who } => { - EvmDataWriter::new_with_selector(1889567281u32).write(who).build() + Writer::new_with_selector(1889567281u32).write(who).build() } Self::burn { from, value } => { - EvmDataWriter::new_with_selector(2646777772u32) - .write(from) - .write(value) - .build() - } - Self::clear_metadata {} => { - EvmDataWriter::new_with_selector(4021736498u32).build() + Writer::new_with_selector(2646777772u32).write(from).write(value).build() } - Self::decimals {} => EvmDataWriter::new_with_selector(826074471u32).build(), + Self::clear_metadata {} => Writer::new_with_selector(4021736498u32).build(), + Self::decimals {} => Writer::new_with_selector(826074471u32).build(), Self::eip2612_domain_separator {} => { - EvmDataWriter::new_with_selector(910484757u32).build() + Writer::new_with_selector(910484757u32).build() } Self::eip2612_nonces { owner } => { - EvmDataWriter::new_with_selector(2127478272u32).write(owner).build() + Writer::new_with_selector(2127478272u32).write(owner).build() } Self::eip2612_permit { owner, spender, value, deadline, v, r, s } => { - EvmDataWriter::new_with_selector(3573918927u32) + Writer::new_with_selector(3573918927u32) .write(owner) .write(spender) .write(value) @@ -953,57 +948,45 @@ where .build() } Self::freeze { account } => { - EvmDataWriter::new_with_selector(2367676207u32).write(account).build() - } - Self::freeze_asset {} => { - EvmDataWriter::new_with_selector(3566436177u32).build() + Writer::new_with_selector(2367676207u32).write(account).build() } + Self::freeze_asset {} => Writer::new_with_selector(3566436177u32).build(), Self::mint { to, value } => { - EvmDataWriter::new_with_selector(1086394137u32) - .write(to) - .write(value) - .build() + Writer::new_with_selector(1086394137u32).write(to).write(value).build() } - Self::name {} => EvmDataWriter::new_with_selector(117300739u32).build(), + Self::name {} => Writer::new_with_selector(117300739u32).build(), Self::set_metadata { name, symbol, decimals } => { - EvmDataWriter::new_with_selector(936559348u32) + Writer::new_with_selector(936559348u32) .write(name) .write(symbol) .write(decimals) .build() } Self::set_team { issuer, admin, freezer } => { - EvmDataWriter::new_with_selector(3352902745u32) + Writer::new_with_selector(3352902745u32) .write(issuer) .write(admin) .write(freezer) .build() } - Self::symbol {} => EvmDataWriter::new_with_selector(2514000705u32).build(), + Self::symbol {} => Writer::new_with_selector(2514000705u32).build(), Self::thaw { account } => { - EvmDataWriter::new_with_selector(1587675670u32).write(account).build() - } - Self::thaw_asset {} => { - EvmDataWriter::new_with_selector(1374431959u32).build() - } - Self::total_supply {} => { - EvmDataWriter::new_with_selector(404098525u32).build() + Writer::new_with_selector(1587675670u32).write(account).build() } + Self::thaw_asset {} => Writer::new_with_selector(1374431959u32).build(), + Self::total_supply {} => Writer::new_with_selector(404098525u32).build(), Self::transfer { to, value } => { - EvmDataWriter::new_with_selector(2835717307u32) - .write(to) - .write(value) - .build() + Writer::new_with_selector(2835717307u32).write(to).write(value).build() } Self::transfer_from { from, to, value } => { - EvmDataWriter::new_with_selector(599290589u32) + Writer::new_with_selector(599290589u32) .write(from) .write(to) .write(value) .build() } Self::transfer_ownership { owner } => { - EvmDataWriter::new_with_selector(4076725131u32).write(owner).build() + Writer::new_with_selector(4076725131u32).write(owner).build() } Self::__phantom(_, _) => { ::core::panicking::panic_fmt( @@ -1049,8 +1032,8 @@ pub(crate) fn __PrecompileSet_test_solidity_signatures_inner() where Runtime: Get, { - use ::precompile_utils::data::EvmData; - match (&"(address,address)", &<(Address, Address) as EvmData>::solidity_type()) { + use ::precompile_utils::solidity::Codec; + match (&"(address,address)", &<(Address, Address) as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; @@ -1068,7 +1051,7 @@ where } } }; - match (&"(address,uint256)", &<(Address, U256) as EvmData>::solidity_type()) { + match (&"(address,uint256)", &<(Address, U256) as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; @@ -1086,7 +1069,7 @@ where } } }; - match (&"(address)", &<(Address,) as EvmData>::solidity_type()) { + match (&"(address)", &<(Address,) as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; @@ -1104,7 +1087,7 @@ where } } }; - match (&"(address,uint256)", &<(Address, U256) as EvmData>::solidity_type()) { + match (&"(address,uint256)", &<(Address, U256) as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; @@ -1122,7 +1105,7 @@ where } } }; - match (&"()", &<() as EvmData>::solidity_type()) { + match (&"()", &<() as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; @@ -1140,7 +1123,7 @@ where } } }; - match (&"()", &<() as EvmData>::solidity_type()) { + match (&"()", &<() as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; @@ -1158,7 +1141,7 @@ where } } }; - match (&"()", &<() as EvmData>::solidity_type()) { + match (&"()", &<() as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; @@ -1176,7 +1159,7 @@ where } } }; - match (&"(address)", &<(Address,) as EvmData>::solidity_type()) { + match (&"(address)", &<(Address,) as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; @@ -1196,7 +1179,7 @@ where }; match ( &"(address,address,uint256,uint256,uint8,bytes32,bytes32)", - &<(Address, Address, U256, U256, u8, H256, H256) as EvmData>::solidity_type(), + &<(Address, Address, U256, U256, u8, H256, H256) as Codec>::signature(), ) { (left_val, right_val) => { if !(*left_val == *right_val) { @@ -1215,7 +1198,7 @@ where } } }; - match (&"(address)", &<(Address,) as EvmData>::solidity_type()) { + match (&"(address)", &<(Address,) as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; @@ -1233,7 +1216,7 @@ where } } }; - match (&"()", &<() as EvmData>::solidity_type()) { + match (&"()", &<() as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; @@ -1251,7 +1234,7 @@ where } } }; - match (&"(address,uint256)", &<(Address, U256) as EvmData>::solidity_type()) { + match (&"(address,uint256)", &<(Address, U256) as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; @@ -1269,7 +1252,7 @@ where } } }; - match (&"()", &<() as EvmData>::solidity_type()) { + match (&"()", &<() as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; @@ -1293,7 +1276,7 @@ where BoundedString>, BoundedString>, u8, - ) as EvmData>::solidity_type(), + ) as Codec>::signature(), ) { (left_val, right_val) => { if !(*left_val == *right_val) { @@ -1314,7 +1297,7 @@ where }; match ( &"(address,address,address)", - &<(Address, Address, Address) as EvmData>::solidity_type(), + &<(Address, Address, Address) as Codec>::signature(), ) { (left_val, right_val) => { if !(*left_val == *right_val) { @@ -1333,7 +1316,7 @@ where } } }; - match (&"()", &<() as EvmData>::solidity_type()) { + match (&"()", &<() as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; @@ -1351,7 +1334,7 @@ where } } }; - match (&"(address)", &<(Address,) as EvmData>::solidity_type()) { + match (&"(address)", &<(Address,) as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; @@ -1369,7 +1352,7 @@ where } } }; - match (&"()", &<() as EvmData>::solidity_type()) { + match (&"()", &<() as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; @@ -1387,7 +1370,7 @@ where } } }; - match (&"()", &<() as EvmData>::solidity_type()) { + match (&"()", &<() as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; @@ -1405,7 +1388,7 @@ where } } }; - match (&"(address,uint256)", &<(Address, U256) as EvmData>::solidity_type()) { + match (&"(address,uint256)", &<(Address, U256) as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; @@ -1425,7 +1408,7 @@ where }; match ( &"(address,address,uint256)", - &<(Address, Address, U256) as EvmData>::solidity_type(), + &<(Address, Address, U256) as Codec>::signature(), ) { (left_val, right_val) => { if !(*left_val == *right_val) { @@ -1444,7 +1427,7 @@ where } } }; - match (&"(address)", &<(Address,) as EvmData>::solidity_type()) { + match (&"(address)", &<(Address,) as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; diff --git a/precompiles/utils/macro/tests/expand/returns_tuple.expanded.rs b/precompiles/utils/macro/tests/expand/returns_tuple.expanded.rs index f0cbf1b9a4..222b61d39c 100644 --- a/precompiles/utils/macro/tests/expand/returns_tuple.expanded.rs +++ b/precompiles/utils/macro/tests/expand/returns_tuple.expanded.rs @@ -22,7 +22,7 @@ impl ExamplePrecompileCall { pub fn parse_call_data( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::RevertReason; + use ::precompile_utils::solidity::revert::RevertReason; let input = handle.input(); let selector = input .get(0..4) @@ -40,9 +40,9 @@ impl ExamplePrecompileCall { fn _parse_example( handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult { - use ::precompile_utils::revert::InjectBacktrace; - use ::precompile_utils::modifier::FunctionModifier; - use ::precompile_utils::handle::PrecompileHandleExt; + use ::precompile_utils::solidity::revert::InjectBacktrace; + use ::precompile_utils::solidity::modifier::FunctionModifier; + use ::precompile_utils::evm::handle::PrecompileHandleExt; handle.check_function_modifier(FunctionModifier::NonPayable)?; Ok(Self::example {}) } @@ -50,13 +50,13 @@ impl ExamplePrecompileCall { self, handle: &mut impl PrecompileHandle, ) -> ::precompile_utils::EvmResult<::fp_evm::PrecompileOutput> { - use ::precompile_utils::data::EvmDataWriter; + use ::precompile_utils::solidity::codec::Writer; use ::fp_evm::{PrecompileOutput, ExitSucceed}; let output = match self { Self::example {} => { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::{Codec, Writer}; let output = ::example(handle); - ::precompile_utils::data::encode_as_function_return_value(output?) + Codec::encode_for_function(output?) } Self::__phantom(_, _) => { ::core::panicking::panic_fmt( @@ -82,9 +82,9 @@ impl ExamplePrecompileCall { &[1412775727u32] } pub fn encode(self) -> ::sp_std::vec::Vec { - use ::precompile_utils::EvmDataWriter; + use ::precompile_utils::solidity::codec::Writer; match self { - Self::example {} => EvmDataWriter::new_with_selector(1412775727u32).build(), + Self::example {} => Writer::new_with_selector(1412775727u32).build(), Self::__phantom(_, _) => { ::core::panicking::panic_fmt( format_args!("__phantom variant should not be used"), @@ -107,8 +107,8 @@ impl ::fp_evm::Precompile for ExamplePrecompile { } #[allow(non_snake_case)] pub(crate) fn __ExamplePrecompile_test_solidity_signatures_inner() { - use ::precompile_utils::data::EvmData; - match (&"()", &<() as EvmData>::solidity_type()) { + use ::precompile_utils::solidity::Codec; + match (&"()", &<() as Codec>::signature()) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = ::core::panicking::AssertKind::Eq; diff --git a/precompiles/utils/macro/tests/pass/derive_evm_data.rs b/precompiles/utils/macro/tests/pass/derive_codec.rs similarity index 72% rename from precompiles/utils/macro/tests/pass/derive_evm_data.rs rename to precompiles/utils/macro/tests/pass/derive_codec.rs index 6d275a253b..c23f5611da 100644 --- a/precompiles/utils/macro/tests/pass/derive_evm_data.rs +++ b/precompiles/utils/macro/tests/pass/derive_codec.rs @@ -14,16 +14,16 @@ // You should have received a copy of the GNU General Public License // along with Moonbeam. If not, see . -use precompile_utils::data::{EvmData, Address, EvmDataReader, EvmDataWriter}; +use precompile_utils::solidity::codec::{Address, Codec, Reader, Writer}; use sp_core::H160; -#[derive(Debug, Clone, PartialEq, Eq, EvmData)] +#[derive(Debug, Clone, PartialEq, Eq, Codec)] struct StaticSize { id: u32, address: Address, } -#[derive(Debug, Clone, PartialEq, Eq, EvmData)] +#[derive(Debug, Clone, PartialEq, Eq, Codec)] struct DynamicSize { id: u32, array: Vec, @@ -33,22 +33,22 @@ fn main() { // static let static_size = StaticSize { id: 5, - address: H160::repeat_byte(0x42).into() + address: H160::repeat_byte(0x42).into(), }; assert!(StaticSize::has_static_size()); - assert_eq!(&StaticSize::solidity_type(), "(uint32,address)"); + assert_eq!(&StaticSize::signature(), "(uint32,address)"); - let bytes = EvmDataWriter::new().write(static_size.clone()).build(); + let bytes = Writer::new().write(static_size.clone()).build(); assert_eq!( bytes, - EvmDataWriter::new() + Writer::new() .write(5u32) .write(Address::from(H160::repeat_byte(0x42))) .build() ); - let mut reader = EvmDataReader::new(&bytes); + let mut reader = Reader::new(&bytes); let static_size_2: StaticSize = reader.read().expect("to decode properly"); assert_eq!(static_size_2, static_size); @@ -58,12 +58,12 @@ fn main() { array: vec![10u32, 15u32], }; assert!(!DynamicSize::::has_static_size()); - assert_eq!(DynamicSize::::solidity_type(), "(uint32,uint32[])"); + assert_eq!(DynamicSize::::signature(), "(uint32,uint32[])"); - let bytes = EvmDataWriter::new().write(dynamic_size.clone()).build(); + let bytes = Writer::new().write(dynamic_size.clone()).build(); assert_eq!( bytes, - EvmDataWriter::new() + Writer::new() .write(0x20u32) // offset of struct .write(6u32) // id .write(0x40u32) // array offset @@ -73,8 +73,7 @@ fn main() { .build() ); - let mut reader = EvmDataReader::new(&bytes); + let mut reader = Reader::new(&bytes); let dynamic_size_2: DynamicSize = reader.read().expect("to decode properly"); assert_eq!(dynamic_size_2, dynamic_size); } - diff --git a/precompiles/utils/macro/tests/pass/precompile_fn_modifiers.rs b/precompiles/utils/macro/tests/pass/precompile_fn_modifiers.rs index 0ded5fc271..7437a11ea9 100644 --- a/precompiles/utils/macro/tests/pass/precompile_fn_modifiers.rs +++ b/precompiles/utils/macro/tests/pass/precompile_fn_modifiers.rs @@ -71,14 +71,14 @@ fn main() { [0u8;20], PrecompileSetCall::view {} ).with_static_call(true) - .execute_returns_encoded(()); + .execute_returns(()); PrecompileSet.prepare_test( [0u8;20], [0u8;20], PrecompileSetCall::payable {} ).with_value(1) - .execute_returns_encoded(()); + .execute_returns(()); PrecompileSet.prepare_test( [0u8;20], diff --git a/precompiles/utils/macro/tests/tests.rs b/precompiles/utils/macro/tests/tests.rs index ea4aff69b2..31326ba618 100644 --- a/precompiles/utils/macro/tests/tests.rs +++ b/precompiles/utils/macro/tests/tests.rs @@ -16,12 +16,6 @@ use sha3::{Digest, Keccak256}; -#[precompile_utils_macro::generate_function_selector] -pub enum Action { - Toto = "toto()", - Tata = "tata()", -} - #[test] fn test_keccak256() { assert_eq!( @@ -38,19 +32,6 @@ fn test_keccak256() { ); } -#[test] -fn test_generate_function_selector() { - assert_eq!( - &(Action::Toto as u32).to_be_bytes()[..], - &Keccak256::digest(b"toto()")[0..4], - ); - assert_eq!( - &(Action::Tata as u32).to_be_bytes()[..], - &Keccak256::digest(b"tata()")[0..4], - ); - assert_ne!(Action::Toto as u32, Action::Tata as u32); -} - #[test] fn ui() { let t = trybuild::TestCases::new(); diff --git a/precompiles/utils/src/costs.rs b/precompiles/utils/src/evm/costs.rs similarity index 100% rename from precompiles/utils/src/costs.rs rename to precompiles/utils/src/evm/costs.rs diff --git a/precompiles/utils/src/handle.rs b/precompiles/utils/src/evm/handle.rs similarity index 84% rename from precompiles/utils/src/handle.rs rename to precompiles/utils/src/evm/handle.rs index 64fef18abc..a468fa9af3 100644 --- a/precompiles/utils/src/handle.rs +++ b/precompiles/utils/src/evm/handle.rs @@ -15,7 +15,14 @@ // along with Moonbeam. If not, see . use { - crate::{data::EvmDataReader, modifier::FunctionModifier, revert::MayRevert, EvmResult}, + crate::{ + solidity::{ + codec::Reader, + modifier::FunctionModifier, + revert::{MayRevert, RevertReason}, + }, + EvmResult, + }, fp_evm::{Log, PrecompileHandle}, }; @@ -34,19 +41,13 @@ pub trait PrecompileHandleExt: PrecompileHandle { /// called into. fn check_function_modifier(&self, modifier: FunctionModifier) -> MayRevert; - #[must_use] - /// Read the selector from the input data. - fn read_selector(&self) -> MayRevert - where - T: num_enum::TryFromPrimitive; - #[must_use] /// Read the selector from the input data. fn read_u32_selector(&self) -> MayRevert; #[must_use] /// Returns a reader of the input, skipping the selector. - fn read_after_selector(&self) -> MayRevert; + fn read_after_selector(&self) -> MayRevert; } impl PrecompileHandleExt for T { @@ -54,7 +55,7 @@ impl PrecompileHandleExt for T { /// This can be useful to record log costs early when their content have static size. #[must_use] fn record_log_costs_manual(&mut self, topics: usize, data_len: usize) -> EvmResult { - self.record_cost(crate::costs::log_costs(topics, data_len)?)?; + self.record_cost(crate::evm::costs::log_costs(topics, data_len)?)?; Ok(()) } @@ -73,28 +74,24 @@ impl PrecompileHandleExt for T { /// Check that a function call is compatible with the context it is /// called into. fn check_function_modifier(&self, modifier: FunctionModifier) -> MayRevert { - crate::modifier::check_function_modifier(self.context(), self.is_static(), modifier) - } - - #[must_use] - /// Read the selector from the input data. - fn read_selector(&self) -> MayRevert - where - S: num_enum::TryFromPrimitive, - { - EvmDataReader::read_selector(self.input()) + crate::solidity::modifier::check_function_modifier( + self.context(), + self.is_static(), + modifier, + ) } #[must_use] /// Read the selector from the input data as u32. fn read_u32_selector(&self) -> MayRevert { - EvmDataReader::read_u32_selector(self.input()) + crate::solidity::codec::selector(self.input()) + .ok_or(RevertReason::read_out_of_bounds("selector").into()) } #[must_use] /// Returns a reader of the input, skipping the selector. - fn read_after_selector(&self) -> MayRevert { - EvmDataReader::new_skip_selector(self.input()) + fn read_after_selector(&self) -> MayRevert { + Reader::new_skip_selector(self.input()) } } diff --git a/precompiles/utils/src/logs.rs b/precompiles/utils/src/evm/logs.rs similarity index 97% rename from precompiles/utils/src/logs.rs rename to precompiles/utils/src/evm/logs.rs index 85238bc9d3..2dde6ff126 100644 --- a/precompiles/utils/src/logs.rs +++ b/precompiles/utils/src/evm/logs.rs @@ -103,6 +103,6 @@ impl LogExt for Log { } fn compute_cost(&self) -> EvmResult { - crate::costs::log_costs(self.topics.len(), self.data.len()) + crate::evm::costs::log_costs(self.topics.len(), self.data.len()) } } diff --git a/precompiles/utils/src/evm/mod.rs b/precompiles/utils/src/evm/mod.rs new file mode 100644 index 0000000000..6b4cc27f82 --- /dev/null +++ b/precompiles/utils/src/evm/mod.rs @@ -0,0 +1,19 @@ +// Copyright 2019-2023 PureStake Inc. +// This file is part of Moonbeam. + +// Moonbeam is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Moonbeam is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Moonbeam. If not, see . + +pub mod costs; +pub mod handle; +pub mod logs; diff --git a/precompiles/utils/src/lib.rs b/precompiles/utils/src/lib.rs index 81c0e4e134..e01596e31a 100644 --- a/precompiles/utils/src/lib.rs +++ b/precompiles/utils/src/lib.rs @@ -18,59 +18,29 @@ extern crate alloc; -// Allows to use inside this crate `EvmData` derive macro,which depends on +// Allows to use inside this crate `solidity::Codec` derive macro,which depends on // `precompile_utils` being in the list of imported crates. extern crate self as precompile_utils; -pub mod costs; -pub mod handle; -pub mod logs; -pub mod modifier; +pub mod evm; pub mod precompile_set; -pub mod revert; pub mod substrate; +pub mod solidity; + #[cfg(feature = "testing")] pub mod testing; #[cfg(test)] mod tests; -use crate::alloc::{borrow::ToOwned, vec::Vec}; -use fp_evm::{ExitRevert, ExitSucceed, PrecompileFailure, PrecompileOutput}; +use fp_evm::PrecompileFailure; -pub mod data; +// pub mod data; -pub use data::{EvmData, EvmDataReader, EvmDataWriter}; +// pub use data::{solidity::Codec, Reader, Writer}; pub use fp_evm::Precompile; -pub use precompile_utils_macro::{ - generate_function_selector, keccak256, precompile, precompile_name_from_address, -}; - -/// Generated a `PrecompileFailure::Revert` with proper encoding for the output. -/// If the revert needs improved formatting such as backtraces, `Revert` type should -/// be used instead. -#[must_use] -pub fn revert(output: impl AsRef<[u8]>) -> PrecompileFailure { - PrecompileFailure::Revert { - exit_status: ExitRevert::Reverted, - output: encoded_revert(output), - } -} - -pub fn encoded_revert(output: impl AsRef<[u8]>) -> Vec { - EvmDataWriter::new_with_selector(revert::RevertSelector::Generic) - .write::(output.as_ref().to_owned().into()) - .build() -} - -#[must_use] -pub fn succeed(output: impl AsRef<[u8]>) -> PrecompileOutput { - PrecompileOutput { - exit_status: ExitSucceed::Returned, - output: output.as_ref().to_owned(), - } -} +pub use precompile_utils_macro::{keccak256, precompile, precompile_name_from_address}; /// Alias for Result returning an EVM precompile error. pub type EvmResult = Result; @@ -78,19 +48,35 @@ pub type EvmResult = Result; pub mod prelude { pub use { crate::{ - data::{ - Address, BoundedBytes, BoundedString, BoundedVec, EvmData, EvmDataReader, - EvmDataWriter, SolidityConvert, UnboundedBytes, UnboundedString, + evm::{ + handle::PrecompileHandleExt, + logs::{log0, log1, log2, log3, log4, LogExt}, + }, + solidity::{ + // We export solidity itself to encourage using `solidity::Codec` to avoid confusion + // with parity_scale_codec, + self, + codec::{ + Address, + BoundedBytes, + BoundedString, + BoundedVec, + // Allow usage of Codec methods while not exporting the name directly. + Codec as _, + Convert, + UnboundedBytes, + UnboundedString, + }, + revert::{ + revert, BacktraceExt, InjectBacktrace, MayRevert, Revert, RevertExt, + RevertReason, + }, }, - handle::{with_precompile_handle, PrecompileHandleExt}, - logs::{log0, log1, log2, log3, log4, LogExt}, - modifier::{check_function_modifier, FunctionModifier}, - revert, - revert::{BacktraceExt, InjectBacktrace, MayRevert, Revert, RevertExt, RevertReason}, substrate::{RuntimeHelper, TryDispatchError}, - succeed, EvmResult, + EvmResult, }, + alloc::string::String, pallet_evm::{PrecompileHandle, PrecompileOutput}, - precompile_utils_macro::{generate_function_selector, keccak256, precompile}, + precompile_utils_macro::{keccak256, precompile}, }; } diff --git a/precompiles/utils/src/precompile_set.rs b/precompiles/utils/src/precompile_set.rs index 394299e729..844057a345 100644 --- a/precompiles/utils/src/precompile_set.rs +++ b/precompiles/utils/src/precompile_set.rs @@ -14,11 +14,14 @@ // You should have received a copy of the GNU General Public License // along with Moonbeam. If not, see . -//! Provide utils assemble precompiles and precompilesets into a +//! Provide utils to assemble precompiles and precompilesets into a //! final precompile set with security checks. All security checks are enabled by //! default and must be disabled explicely throught type annotations. -use crate::{data::String, revert, substrate::RuntimeHelper}; +use crate::{ + solidity::{codec::String, revert::revert}, + substrate::RuntimeHelper, +}; use fp_evm::{Precompile, PrecompileHandle, PrecompileResult, PrecompileSet}; use frame_support::pallet_prelude::Get; use impl_trait_for_tuples::impl_for_tuples; @@ -381,7 +384,7 @@ impl<'a, H: PrecompileHandle> PrecompileHandle for RestrictiveHandle<'a, H> { if !self.allow_subcalls { return ( evm::ExitReason::Revert(evm::ExitRevert::Reverted), - crate::encoded_revert("subcalls disabled for this precompile"), + crate::solidity::revert::revert_as_bytes("subcalls disabled for this precompile"), ); } diff --git a/precompiles/utils/src/data/bytes.rs b/precompiles/utils/src/solidity/codec/bytes.rs similarity index 91% rename from precompiles/utils/src/data/bytes.rs rename to precompiles/utils/src/solidity/codec/bytes.rs index 31736dd41a..c3c72b8fb0 100644 --- a/precompiles/utils/src/data/bytes.rs +++ b/precompiles/utils/src/solidity/codec/bytes.rs @@ -15,6 +15,8 @@ // along with Moonbeam. If not, see . use super::*; +use alloc::borrow::ToOwned; +use sp_core::{ConstU32, Get}; type ConstU32Max = ConstU32<{ u32::MAX }>; @@ -25,14 +27,14 @@ pub type UnboundedString = BoundedBytesString; pub type BoundedString = BoundedBytesString; trait Kind { - fn solidity_type() -> String; + fn signature() -> String; } #[derive(Clone, Debug, Eq, PartialEq)] pub struct BytesKind; impl Kind for BytesKind { - fn solidity_type() -> String { + fn signature() -> String { String::from("bytes") } } @@ -41,7 +43,7 @@ impl Kind for BytesKind { pub struct StringKind; impl Kind for StringKind { - fn solidity_type() -> String { + fn signature() -> String { String::from("string") } } @@ -82,8 +84,8 @@ impl> BoundedBytesString { } } -impl> EvmData for BoundedBytesString { - fn read(reader: &mut EvmDataReader) -> MayRevert { +impl> Codec for BoundedBytesString { + fn read(reader: &mut Reader) -> MayRevert { let mut inner_reader = reader.read_pointer()?; // Read bytes/string size. @@ -103,7 +105,7 @@ impl> EvmData for BoundedBytesString { let data = inner_reader .input .get(range) - .ok_or_else(|| RevertReason::read_out_of_bounds(K::solidity_type()))?; + .ok_or_else(|| RevertReason::read_out_of_bounds(K::signature()))?; let bytes = Self { data: data.to_owned(), @@ -113,7 +115,7 @@ impl> EvmData for BoundedBytesString { Ok(bytes) } - fn write(writer: &mut EvmDataWriter, value: Self) { + fn write(writer: &mut Writer, value: Self) { let value: Vec<_> = value.into(); let length = value.len(); @@ -130,7 +132,7 @@ impl> EvmData for BoundedBytesString { value.resize(padded_size, 0); writer.write_pointer( - EvmDataWriter::new() + Writer::new() .write(U256::from(length)) .write_raw_bytes(&value) .build(), @@ -141,8 +143,8 @@ impl> EvmData for BoundedBytesString { false } - fn solidity_type() -> String { - K::solidity_type() + fn signature() -> String { + K::signature() } } diff --git a/precompiles/utils/src/data/mod.rs b/precompiles/utils/src/solidity/codec/mod.rs similarity index 60% rename from precompiles/utils/src/data/mod.rs rename to precompiles/utils/src/solidity/codec/mod.rs index 8b076a3c54..ea27fb6330 100644 --- a/precompiles/utils/src/data/mod.rs +++ b/precompiles/utils/src/solidity/codec/mod.rs @@ -1,4 +1,4 @@ -// Copyright 2019-2022 PureStake Inc. +// Copyright 2019-2023 PureStake Inc. // This file is part of Moonbeam. // Moonbeam is free software: you can redistribute it and/or modify @@ -14,90 +14,115 @@ // You should have received a copy of the GNU General Public License // along with Moonbeam. If not, see . +//! Solidity encoding following the +//! [Contract ABI Specification](https://docs.soliditylang.org/en/v0.8.19/abi-spec.html#abi) + pub mod bytes; pub mod native; + +#[cfg(any(feature = "codec-xcm", test))] pub mod xcm; -pub use affix::paste; +use crate::solidity::revert::{MayRevert, RevertReason}; +use core::{marker::PhantomData, ops::Range}; +use sp_core::{H256, U256}; +use sp_std::{convert::TryInto, vec, vec::Vec}; + pub use alloc::string::String; -pub use bytes::*; -pub use native::*; - -use { - crate::revert::{InjectBacktrace, MayRevert, RevertReason}, - alloc::borrow::ToOwned, - core::{any::type_name, marker::PhantomData, ops::Range}, - frame_support::traits::{ConstU32, Get}, - impl_trait_for_tuples::impl_for_tuples, - sp_core::{H160, H256, U256}, - sp_std::{convert::TryInto, vec, vec::Vec}, -}; +pub use bytes::{BoundedBytes, BoundedString, UnboundedBytes, UnboundedString}; +pub use native::{Address, BoundedVec}; // derive macro -pub use precompile_utils_macro::EvmData; +pub use precompile_utils_macro::Codec; -/// Data that can be converted from and to EVM data types. -pub trait EvmData: Sized { - fn read(reader: &mut EvmDataReader) -> MayRevert; - fn write(writer: &mut EvmDataWriter, value: Self); +/// Data that can be encoded/encoded followiong the Solidity ABI Specification. +pub trait Codec: Sized { + fn read(reader: &mut Reader) -> MayRevert; + fn write(writer: &mut Writer, value: Self); fn has_static_size() -> bool; - fn solidity_type() -> String; + fn signature() -> String; fn is_explicit_tuple() -> bool { false } } -/// Wrapper around an EVM input slice, helping to parse it. -/// Provide functions to parse common types. -#[derive(Clone, Copy, Debug)] -pub struct EvmDataReader<'a> { - input: &'a [u8], - cursor: usize, +/// Encode the value into its Solidity ABI format. +/// If `T` is a tuple it is encoded as a Solidity tuple with dynamic-size offset. +fn encode(value: T) -> Vec { + Writer::new().write(value).build() } -impl<'a> EvmDataReader<'a> { - /// Create a new input parser. - pub fn new(input: &'a [u8]) -> Self { - Self { input, cursor: 0 } +/// Encode the value into its Solidity ABI format. +/// If `T` is a tuple every element is encoded without a prefixed offset. +/// It matches the encoding of Solidity function arguments and return value, or event data. +pub fn encode_arguments(value: T) -> Vec { + let output = encode(value); + if T::is_explicit_tuple() && !T::has_static_size() { + output[32..].to_vec() + } else { + output } +} - /// Create a new input parser from a selector-initial input. - pub fn read_selector(input: &'a [u8]) -> MayRevert - where - T: num_enum::TryFromPrimitive, - { - if input.len() < 4 { - return Err(RevertReason::read_out_of_bounds("selector").into()); - } +pub use self::encode_arguments as encode_return_value; +pub use self::encode_arguments as encode_event_data; - let mut buffer = [0u8; 4]; - buffer.copy_from_slice(&input[0..4]); - let selector = T::try_from_primitive(u32::from_be_bytes(buffer)).map_err(|_| { - log::trace!( - target: "precompile-utils", - "Failed to match function selector for {}", - type_name::() - ); - RevertReason::UnknownSelector - })?; - - Ok(selector) +/// Encode the value as the arguments of a Solidity function with given selector. +/// If `T` is a tuple each member represents an argument of the function. +pub fn encode_with_selector(selector: u32, value: T) -> Vec { + Writer::new_with_selector(selector) + .write_raw_bytes(&encode_arguments(value)) + .build() +} + +/// Decode the value from its Solidity ABI format. +/// If `T` is a tuple it is decoded as a Solidity tuple with dynamic-size offset. +fn decode(input: &[u8]) -> MayRevert { + Reader::new(input).read() +} + +/// Decode the value from its Solidity ABI format. +/// If `T` is a tuple every element is decoded without a prefixed offset. +/// It matches the encoding of Solidity function arguments and return value, or event data. +pub fn decode_arguments(input: &[u8]) -> MayRevert { + if T::is_explicit_tuple() && !T::has_static_size() { + let writer = Writer::new(); + let mut writer = writer.write(U256::from(32)); + writer.write_pointer(input.to_vec()); + let input = writer.build(); + decode(&input) + } else { + decode(&input) } +} - /// Read selector as u32 - pub fn read_u32_selector(input: &'a [u8]) -> MayRevert { - if input.len() < 4 { - return Err(RevertReason::read_out_of_bounds("selector").into()); - } +pub use self::decode_arguments as decode_return_value; +pub use self::decode_arguments as decode_event_data; +/// Extracts the selector from the start of the input, or returns `None` if the input is too short. +pub fn selector(input: &[u8]) -> Option { + input.get(0..4).map(|s| { let mut buffer = [0u8; 4]; - buffer.copy_from_slice(&input[0..4]); + buffer.copy_from_slice(s); + u32::from_be_bytes(buffer) + }) +} - Ok(u32::from_be_bytes(buffer)) +/// Wrapper around an EVM input slice. +#[derive(Clone, Copy, Debug)] +pub struct Reader<'inner> { + input: &'inner [u8], + cursor: usize, +} + +impl<'inner> Reader<'inner> { + /// Create a Reader. + pub fn new(input: &'inner [u8]) -> Self { + Self { input, cursor: 0 } } - /// Create a new input parser from a selector-initial input. - pub fn new_skip_selector(input: &'a [u8]) -> MayRevert { + /// Create a Reader while skipping an initial selector. + pub fn new_skip_selector(input: &'inner [u8]) -> MayRevert { if input.len() < 4 { return Err(RevertReason::read_out_of_bounds("selector").into()); } @@ -106,7 +131,7 @@ impl<'a> EvmDataReader<'a> { } /// Check the input has at least the correct amount of arguments before the end (32 bytes values). - pub fn expect_arguments(&self, args: usize) -> MayRevert<()> { + pub fn expect_arguments(&self, args: usize) -> MayRevert { if self.input.len() >= self.cursor + args * 32 { Ok(()) } else { @@ -115,7 +140,7 @@ impl<'a> EvmDataReader<'a> { } /// Read data from the input. - pub fn read(&mut self) -> MayRevert { + pub fn read(&mut self) -> MayRevert { T::read(self) } @@ -182,18 +207,18 @@ impl<'a> EvmDataReader<'a> { /// Help build an EVM input/output data. /// /// Functions takes `self` to allow chaining all calls like -/// `EvmDataWriter::new().write(...).write(...).build()`. +/// `Writer::new().write(...).write(...).build()`. /// While it could be more ergonomic to take &mut self, this would /// prevent to have a `build` function that don't clone the output. #[derive(Clone, Debug)] -pub struct EvmDataWriter { +pub struct Writer { pub(crate) data: Vec, - offset_data: Vec, + offset_data: Vec, selector: Option, } #[derive(Clone, Debug)] -struct OffsetDatum { +struct OffsetChunk { // Offset location in the container data. offset_position: usize, // Data pointed by the offset that must be inserted at the end of container data. @@ -203,7 +228,7 @@ struct OffsetDatum { offset_shift: usize, } -impl EvmDataWriter { +impl Writer { /// Creates a new empty output builder (without selector). pub fn new() -> Self { Self { @@ -224,7 +249,7 @@ impl EvmDataWriter { } } - /// Return the built data. + // Return the built data. pub fn build(mut self) -> Vec { Self::bake_offsets(&mut self.data, self.offset_data); @@ -238,9 +263,9 @@ impl EvmDataWriter { } /// Add offseted data at the end of this writer's data, updating the offsets. - fn bake_offsets(output: &mut Vec, offsets: Vec) { - for mut offset_datum in offsets { - let offset_position = offset_datum.offset_position; + fn bake_offsets(output: &mut Vec, offsets: Vec) { + for mut offset_chunk in offsets { + let offset_position = offset_chunk.offset_position; let offset_position_end = offset_position + 32; // The offset is the distance between the start of the data and the @@ -248,14 +273,14 @@ impl EvmDataWriter { // Offsets in inner data are relative to the start of their respective "container". // However in arrays the "container" is actually the item itself instead of the whole // array, which is corrected by `offset_shift`. - let free_space_offset = output.len() - offset_datum.offset_shift; + let free_space_offset = output.len() - offset_chunk.offset_shift; // Override dummy offset to the offset it will be in the final output. U256::from(free_space_offset) .to_big_endian(&mut output[offset_position..offset_position_end]); // Append this data at the end of the current output. - output.append(&mut offset_datum.data); + output.append(&mut offset_chunk.data); } } @@ -267,7 +292,7 @@ impl EvmDataWriter { } /// Write data of requested type. - pub fn write(mut self, value: T) -> Self { + pub fn write(mut self, value: T) -> Self { T::write(&mut self, value); self } @@ -277,12 +302,12 @@ impl EvmDataWriter { /// Initially write a dummy value as offset in this writer's data, which will be replaced by /// the correct offset once the pointed data is appended. /// - /// Takes `&mut self` since its goal is to be used inside `EvmData` impl and not in chains. + /// Takes `&mut self` since its goal is to be used inside `solidity::Codec` impl and not in chains. pub fn write_pointer(&mut self, data: Vec) { let offset_position = self.data.len(); H256::write(self, H256::repeat_byte(0xff)); - self.offset_data.push(OffsetDatum { + self.offset_data.push(OffsetChunk { offset_position, data, offset_shift: 0, @@ -290,22 +315,16 @@ impl EvmDataWriter { } } -impl Default for EvmDataWriter { - fn default() -> Self { - Self::new() - } -} - /// Adapter to parse data as a first type then convert it to another one. /// Useful for old precompiles in which Solidity arguments where set larger than /// the needed Rust type. #[derive(Clone, Copy, Debug)] -pub struct SolidityConvert { +pub struct Convert { inner: C, _phantom: PhantomData

, } -impl From for SolidityConvert { +impl From for Convert { fn from(value: C) -> Self { Self { inner: value, @@ -314,21 +333,21 @@ impl From for SolidityConvert { } } -impl SolidityConvert { +impl Convert { pub fn converted(self) -> C { self.inner } } -impl EvmData for SolidityConvert +impl Codec for Convert where - P: EvmData + TryInto, - C: EvmData + Into

, + P: Codec + TryInto, + C: Codec + Into

, { - fn read(reader: &mut EvmDataReader) -> MayRevert { + fn read(reader: &mut Reader) -> MayRevert { let c = P::read(reader)? .try_into() - .map_err(|_| RevertReason::value_is_too_large(C::solidity_type()))?; + .map_err(|_| RevertReason::value_is_too_large(C::signature()))?; Ok(Self { inner: c, @@ -336,7 +355,7 @@ where }) } - fn write(writer: &mut EvmDataWriter, value: Self) { + fn write(writer: &mut Writer, value: Self) { P::write(writer, value.inner.into()) } @@ -344,18 +363,7 @@ where P::has_static_size() } - fn solidity_type() -> String { - P::solidity_type() - } -} - -/// Wrapper around values being returned by functions. -/// Handle special case with tuple encoding. -pub fn encode_as_function_return_value(value: T) -> Vec { - let output = EvmDataWriter::new().write(value).build(); - if T::is_explicit_tuple() && !T::has_static_size() { - output[32..].to_vec() - } else { - output + fn signature() -> String { + P::signature() } } diff --git a/precompiles/utils/src/data/native.rs b/precompiles/utils/src/solidity/codec/native.rs similarity index 76% rename from precompiles/utils/src/data/native.rs rename to precompiles/utils/src/solidity/codec/native.rs index b466f92eae..1ad1d1ebb9 100644 --- a/precompiles/utils/src/data/native.rs +++ b/precompiles/utils/src/solidity/codec/native.rs @@ -15,30 +15,33 @@ // along with Moonbeam. If not, see . use super::*; +use crate::solidity::revert::InjectBacktrace; +use impl_trait_for_tuples::impl_for_tuples; +use sp_core::{ConstU32, Get, H160}; -impl EvmData for () { - fn read(_reader: &mut EvmDataReader) -> MayRevert { +impl Codec for () { + fn read(_reader: &mut Reader) -> MayRevert { Ok(()) } - fn write(_writer: &mut EvmDataWriter, _value: Self) {} + fn write(_writer: &mut Writer, _value: Self) {} fn has_static_size() -> bool { true } - fn solidity_type() -> String { + fn signature() -> String { String::from("()") } } #[impl_for_tuples(1, 18)] -impl EvmData for Tuple { +impl Codec for Tuple { fn has_static_size() -> bool { for_tuples!(#( Tuple::has_static_size() )&*) } - fn read(reader: &mut EvmDataReader) -> MayRevert { + fn read(reader: &mut Reader) -> MayRevert { if Self::has_static_size() { let mut index = 0; Ok(for_tuples!( ( #( { @@ -57,19 +60,19 @@ impl EvmData for Tuple { } } - fn write(writer: &mut EvmDataWriter, value: Self) { + fn write(writer: &mut Writer, value: Self) { if Self::has_static_size() { for_tuples!( #( Tuple::write(writer, value.Tuple); )* ); } else { - let mut inner_writer = EvmDataWriter::new(); + let mut inner_writer = Writer::new(); for_tuples!( #( Tuple::write(&mut inner_writer, value.Tuple); )* ); writer.write_pointer(inner_writer.build()); } } - fn solidity_type() -> String { + fn signature() -> String { let mut subtypes = Vec::new(); - for_tuples!( #( subtypes.push(Tuple::solidity_type()); )* ); + for_tuples!( #( subtypes.push(Tuple::signature()); )* ); alloc::format!("({})", subtypes.join(",")) } @@ -78,8 +81,8 @@ impl EvmData for Tuple { } } -impl EvmData for H256 { - fn read(reader: &mut EvmDataReader) -> MayRevert { +impl Codec for H256 { + fn read(reader: &mut Reader) -> MayRevert { let range = reader.move_cursor(32)?; let data = reader @@ -90,7 +93,7 @@ impl EvmData for H256 { Ok(H256::from_slice(data)) } - fn write(writer: &mut EvmDataWriter, value: Self) { + fn write(writer: &mut Writer, value: Self) { writer.data.extend_from_slice(value.as_bytes()); } @@ -98,7 +101,7 @@ impl EvmData for H256 { true } - fn solidity_type() -> String { + fn signature() -> String { String::from("bytes32") } } @@ -132,8 +135,8 @@ impl Address { } } -impl EvmData for Address { - fn read(reader: &mut EvmDataReader) -> MayRevert { +impl Codec for Address { + fn read(reader: &mut Reader) -> MayRevert { let range = reader.move_cursor(32)?; let data = reader @@ -144,7 +147,7 @@ impl EvmData for Address { Ok(H160::from_slice(&data[12..32]).into()) } - fn write(writer: &mut EvmDataWriter, value: Self) { + fn write(writer: &mut Writer, value: Self) { H256::write(writer, value.0.into()); } @@ -152,13 +155,13 @@ impl EvmData for Address { true } - fn solidity_type() -> String { + fn signature() -> String { String::from("address") } } -impl EvmData for U256 { - fn read(reader: &mut EvmDataReader) -> MayRevert { +impl Codec for U256 { + fn read(reader: &mut Reader) -> MayRevert { let range = reader.move_cursor(32)?; let data = reader @@ -169,7 +172,7 @@ impl EvmData for U256 { Ok(U256::from_big_endian(data)) } - fn write(writer: &mut EvmDataWriter, value: Self) { + fn write(writer: &mut Writer, value: Self) { let mut buffer = [0u8; 32]; value.to_big_endian(&mut buffer); writer.data.extend_from_slice(&buffer); @@ -179,7 +182,7 @@ impl EvmData for U256 { true } - fn solidity_type() -> String { + fn signature() -> String { String::from("uint256") } } @@ -187,21 +190,21 @@ impl EvmData for U256 { macro_rules! impl_evmdata_for_uints { ($($uint:ty, )*) => { $( - impl EvmData for $uint { - fn read(reader: &mut EvmDataReader) -> MayRevert { + impl Codec for $uint { + fn read(reader: &mut Reader) -> MayRevert { let value256: U256 = reader.read() .map_err(|_| RevertReason::read_out_of_bounds( - Self::solidity_type() + Self::signature() ))?; value256 .try_into() .map_err(|_| RevertReason::value_is_too_large( - Self::solidity_type() + Self::signature() ).into()) } - fn write(writer: &mut EvmDataWriter, value: Self) { + fn write(writer: &mut Writer, value: Self) { U256::write(writer, value.into()); } @@ -209,7 +212,7 @@ macro_rules! impl_evmdata_for_uints { true } - fn solidity_type() -> String { + fn signature() -> String { alloc::format!("uint{}", core::mem::size_of::() * 8) } } @@ -219,14 +222,14 @@ macro_rules! impl_evmdata_for_uints { impl_evmdata_for_uints!(u8, u16, u32, u64, u128,); -impl EvmData for bool { - fn read(reader: &mut EvmDataReader) -> MayRevert { +impl Codec for bool { + fn read(reader: &mut Reader) -> MayRevert { let h256 = H256::read(reader).map_err(|_| RevertReason::read_out_of_bounds("bool"))?; Ok(!h256.is_zero()) } - fn write(writer: &mut EvmDataWriter, value: Self) { + fn write(writer: &mut Writer, value: Self) { let mut buffer = [0u8; 32]; if value { buffer[31] = 1; @@ -239,19 +242,19 @@ impl EvmData for bool { true } - fn solidity_type() -> String { + fn signature() -> String { String::from("bool") } } type ConstU32Max = ConstU32<{ u32::MAX }>; -impl EvmData for Vec { - fn read(reader: &mut EvmDataReader) -> MayRevert { +impl Codec for Vec { + fn read(reader: &mut Reader) -> MayRevert { BoundedVec::::read(reader).map(|x| x.into()) } - fn write(writer: &mut EvmDataWriter, value: Self) { + fn write(writer: &mut Writer, value: Self) { BoundedVec::::write( writer, BoundedVec { @@ -265,8 +268,8 @@ impl EvmData for Vec { false } - fn solidity_type() -> String { - alloc::format!("{}[]", T::solidity_type()) + fn signature() -> String { + alloc::format!("{}[]", T::signature()) } } @@ -277,8 +280,8 @@ pub struct BoundedVec { _phantom: PhantomData, } -impl> EvmData for BoundedVec { - fn read(reader: &mut EvmDataReader) -> MayRevert { +impl> Codec for BoundedVec { + fn read(reader: &mut Reader) -> MayRevert { let mut inner_reader = reader.read_pointer()?; let array_size: usize = inner_reader @@ -293,7 +296,7 @@ impl> EvmData for BoundedVec { let mut array = vec![]; - let mut item_reader = EvmDataReader { + let mut item_reader = Reader { input: inner_reader .input .get(32..) @@ -311,9 +314,9 @@ impl> EvmData for BoundedVec { }) } - fn write(writer: &mut EvmDataWriter, value: Self) { + fn write(writer: &mut Writer, value: Self) { let value: Vec<_> = value.into(); - let mut inner_writer = EvmDataWriter::new().write(U256::from(value.len())); + let mut inner_writer = Writer::new().write(U256::from(value.len())); for inner in value { // Any offset in items are relative to the start of the item instead of the @@ -321,7 +324,7 @@ impl> EvmData for BoundedVec { // all items (offsets) are written. We thus need to rely on `compute_offsets` to do // that, and must store a "shift" to correct the offsets. let shift = inner_writer.data.len(); - let item_writer = EvmDataWriter::new().write(inner); + let item_writer = Writer::new().write(inner); inner_writer = inner_writer.write_raw_bytes(&item_writer.data); for mut offset_datum in item_writer.offset_data { @@ -338,8 +341,8 @@ impl> EvmData for BoundedVec { false } - fn solidity_type() -> String { - alloc::format!("{}[]", T::solidity_type()) + fn signature() -> String { + alloc::format!("{}[]", T::signature()) } } diff --git a/precompiles/utils/src/data/xcm.rs b/precompiles/utils/src/solidity/codec/xcm.rs similarity index 90% rename from precompiles/utils/src/data/xcm.rs rename to precompiles/utils/src/solidity/codec/xcm.rs index b066904de2..d3f740a5e4 100644 --- a/precompiles/utils/src/data/xcm.rs +++ b/precompiles/utils/src/solidity/codec/xcm.rs @@ -17,9 +17,9 @@ //! Encoding of XCM types for solidity use { - crate::{ - data::{BoundedBytes, EvmData, EvmDataReader, EvmDataWriter, UnboundedBytes}, - revert::{InjectBacktrace, MayRevert, RevertReason}, + crate::solidity::{ + codec::{bytes::*, Codec, Reader, Writer}, + revert::{BacktraceExt, InjectBacktrace, MayRevert, RevertReason}, }, alloc::string::String, frame_support::{ensure, traits::ConstU32}, @@ -30,7 +30,7 @@ use { pub const JUNCTION_SIZE_LIMIT: u32 = 2u32.pow(16); // Function to convert network id to bytes -// We don't implement EVMData here as these bytes will be appended only +// We don't implement solidity::Codec here as these bytes will be appended only // to certain Junction variants // Each NetworkId variant is represented as bytes // The first byte represents the enum variant to be used. @@ -113,7 +113,7 @@ pub(crate) fn network_id_from_bytes(encoded_bytes: Vec) -> MayRevert 0, RevertReason::custom("Junctions cannot be empty") ); - let mut encoded_network_id = EvmDataReader::new(&encoded_bytes); + let mut encoded_network_id = Reader::new(&encoded_bytes); let network_selector = encoded_network_id .read_raw_bytes(1) @@ -160,8 +160,8 @@ pub(crate) fn network_id_from_bytes(encoded_bytes: Vec) -> MayRevert MayRevert { +impl Codec for Junction { + fn read(reader: &mut Reader) -> MayRevert { let junction = reader.read::>>()?; let junction_bytes: Vec<_> = junction.into(); @@ -171,7 +171,7 @@ impl EvmData for Junction { ); // For simplicity we use an EvmReader here - let mut encoded_junction = EvmDataReader::new(&junction_bytes); + let mut encoded_junction = Reader::new(&junction_bytes); // We take the first byte let enum_selector = encoded_junction @@ -259,7 +259,7 @@ impl EvmData for Junction { } } - fn write(writer: &mut EvmDataWriter, value: Self) { + fn write(writer: &mut Writer, value: Self) { let mut encoded: Vec = Vec::new(); let encoded_bytes: UnboundedBytes = match value { Junction::Parachain(para_id) => { @@ -314,20 +314,20 @@ impl EvmData for Junction { // type that we need to evaluate how to support _ => unreachable!("Junction::Plurality not supported yet"), }; - EvmData::write(writer, encoded_bytes); + Codec::write(writer, encoded_bytes); } fn has_static_size() -> bool { false } - fn solidity_type() -> String { - UnboundedBytes::solidity_type() + fn signature() -> String { + UnboundedBytes::signature() } } -impl EvmData for Junctions { - fn read(reader: &mut EvmDataReader) -> MayRevert { +impl Codec for Junctions { + fn read(reader: &mut Reader) -> MayRevert { let junctions_bytes: Vec = reader.read()?; let mut junctions = Junctions::Here; for item in junctions_bytes { @@ -339,39 +339,38 @@ impl EvmData for Junctions { Ok(junctions) } - fn write(writer: &mut EvmDataWriter, value: Self) { + fn write(writer: &mut Writer, value: Self) { let encoded: Vec = value.iter().map(|junction| junction.clone()).collect(); - EvmData::write(writer, encoded); + Codec::write(writer, encoded); } fn has_static_size() -> bool { false } - fn solidity_type() -> String { - Vec::::solidity_type() + fn signature() -> String { + Vec::::signature() } } // Cannot used derive macro since it is a foreign struct. -impl EvmData for MultiLocation { - fn read(reader: &mut EvmDataReader) -> MayRevert { - use crate::revert::BacktraceExt; +impl Codec for MultiLocation { + fn read(reader: &mut Reader) -> MayRevert { let (parents, interior) = reader .read() .map_in_tuple_to_field(&["parents", "interior"])?; Ok(MultiLocation { parents, interior }) } - fn write(writer: &mut EvmDataWriter, value: Self) { - EvmData::write(writer, (value.parents, value.interior)); + fn write(writer: &mut Writer, value: Self) { + Codec::write(writer, (value.parents, value.interior)); } fn has_static_size() -> bool { <(u8, Junctions)>::has_static_size() } - fn solidity_type() -> String { - <(u8, Junctions)>::solidity_type() + fn signature() -> String { + <(u8, Junctions)>::signature() } } diff --git a/precompiles/utils/src/solidity/mod.rs b/precompiles/utils/src/solidity/mod.rs new file mode 100644 index 0000000000..13d6d65686 --- /dev/null +++ b/precompiles/utils/src/solidity/mod.rs @@ -0,0 +1,26 @@ +// Copyright 2019-2023 PureStake Inc. +// This file is part of Moonbeam. + +// Moonbeam is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Moonbeam is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Moonbeam. If not, see . + +//! Provides utilities for compatibility with Solidity tooling. + +pub mod codec; +pub mod modifier; +pub mod revert; + +pub use codec::{ + decode_arguments, decode_event_data, decode_return_value, encode_arguments, encode_event_data, + encode_return_value, encode_with_selector, Codec, +}; diff --git a/precompiles/utils/src/modifier.rs b/precompiles/utils/src/solidity/modifier.rs similarity index 97% rename from precompiles/utils/src/modifier.rs rename to precompiles/utils/src/solidity/modifier.rs index 61a8bec290..80e4d33e89 100644 --- a/precompiles/utils/src/modifier.rs +++ b/precompiles/utils/src/solidity/modifier.rs @@ -17,7 +17,7 @@ //! Provide checks related to function modifiers (view/payable). use { - crate::revert::{MayRevert, RevertReason}, + crate::solidity::revert::{MayRevert, RevertReason}, fp_evm::Context, sp_core::U256, }; diff --git a/precompiles/utils/src/revert.rs b/precompiles/utils/src/solidity/revert.rs similarity index 92% rename from precompiles/utils/src/revert.rs rename to precompiles/utils/src/solidity/revert.rs index a19d4f91e5..0b7aa8f5b5 100644 --- a/precompiles/utils/src/revert.rs +++ b/precompiles/utils/src/solidity/revert.rs @@ -17,7 +17,7 @@ //! Utilities to work with revert messages with support for backtraces and //! consistent formatting. -use crate::{data::UnboundedBytes, EvmDataWriter}; +use crate::solidity::{self, codec::bytes::UnboundedBytes}; use alloc::string::{String, ToString}; use fp_evm::{ExitRevert, PrecompileFailure}; use sp_std::vec::Vec; @@ -25,13 +25,21 @@ use sp_std::vec::Vec; /// Represent the result of a computation that can revert. pub type MayRevert = Result; +/// Generate an encoded revert from a simple String. +/// Returns a `PrecompileFailure` that fits in an `EvmResult::Err`. +pub fn revert(msg: impl Into) -> PrecompileFailure { + RevertReason::custom(msg).into() +} + +/// Generate an encoded revert from a simple String. +/// Returns a `Vec` in case `PrecompileFailure` is too high level. +pub fn revert_as_bytes(msg: impl Into) -> Vec { + Revert::new(RevertReason::custom(msg)).to_encoded_bytes() +} + /// Generic error to build abi-encoded revert output. /// See: https://docs.soliditylang.org/en/latest/control-structures.html?highlight=revert#revert -#[precompile_utils_macro::generate_function_selector] -#[derive(Debug, PartialEq)] -pub enum RevertSelector { - Generic = "Error(string)", -} +pub const ERROR_SELECTOR: u32 = 0x08c379a0; #[derive(Clone, PartialEq, Eq)] enum BacktracePart { @@ -166,7 +174,7 @@ impl Revert { /// For all `RevertReason` variants that have a `what` field, change its value. /// Otherwise do nothing. - /// It is useful when writing custom types `EvmData` implementations using + /// It is useful when writing custom types `solidity::Codec` implementations using /// simpler types. pub fn change_what(mut self, what: impl Into) -> Self { let what = what.into(); @@ -181,8 +189,9 @@ impl Revert { } /// Transforms the revert into its bytes representation (from a String). - pub fn to_bytes(self) -> Vec { - self.into() + pub fn to_encoded_bytes(self) -> Vec { + let bytes: Vec = self.into(); + solidity::encode_with_selector(ERROR_SELECTOR, UnboundedBytes::from(bytes)) } } @@ -361,9 +370,7 @@ impl From for PrecompileFailure { fn from(err: Revert) -> Self { PrecompileFailure::Revert { exit_status: ExitRevert::Reverted, - output: EvmDataWriter::new_with_selector(RevertSelector::Generic) - .write::(err.to_string().into()) - .build(), + output: err.to_encoded_bytes(), } } } diff --git a/precompiles/utils/src/substrate.rs b/precompiles/utils/src/substrate.rs index e2f966420c..c0b88bb739 100644 --- a/precompiles/utils/src/substrate.rs +++ b/precompiles/utils/src/substrate.rs @@ -19,7 +19,7 @@ //! - Substrate DB read and write costs use { - crate::{handle::using_precompile_handle, revert}, + crate::{evm::handle::using_precompile_handle, solidity::revert::revert}, core::marker::PhantomData, fp_evm::{ExitError, PrecompileFailure, PrecompileHandle}, frame_support::{ diff --git a/precompiles/utils/src/testing/execution.rs b/precompiles/utils/src/testing/execution.rs index 0a0b6b8191..8e45aaa772 100644 --- a/precompiles/utils/src/testing/execution.rs +++ b/precompiles/utils/src/testing/execution.rs @@ -16,8 +16,8 @@ use { crate::{ + solidity::codec::Codec, testing::{decode_revert_message, MockHandle, PrettyLog, SubcallHandle, SubcallTrait}, - EvmData, EvmDataWriter, }, fp_evm::{ Context, ExitError, ExitSucceed, Log, PrecompileFailure, PrecompileOutput, @@ -153,7 +153,7 @@ impl<'p, P: PrecompileSet> PrecompilesTester<'p, P> { } /// Execute the precompile set and check it returns provided output. - pub fn execute_returns(mut self, output: Vec) { + pub fn execute_returns_raw(mut self, output: Vec) { let res = self.execute(); match res { @@ -192,8 +192,8 @@ impl<'p, P: PrecompileSet> PrecompilesTester<'p, P> { } /// Execute the precompile set and check it returns provided Solidity encoded output. - pub fn execute_returns_encoded(self, output: impl EvmData) { - self.execute_returns(EvmDataWriter::new().write(output).build()) + pub fn execute_returns(self, output: impl Codec) { + self.execute_returns_raw(crate::solidity::encode_return_value(output)) } /// Execute the precompile set and check if it reverts. diff --git a/precompiles/utils/src/testing/handle.rs b/precompiles/utils/src/testing/handle.rs index 8c9c4d5ff9..d97ce9d128 100644 --- a/precompiles/utils/src/testing/handle.rs +++ b/precompiles/utils/src/testing/handle.rs @@ -16,11 +16,13 @@ use { crate::testing::PrettyLog, + evm::{ExitRevert, ExitSucceed}, fp_evm::{Context, ExitError, ExitReason, Log, PrecompileHandle, Transfer}, sp_core::{H160, H256}, sp_std::boxed::Box, }; +#[derive(Debug, Clone)] pub struct Subcall { pub address: H160, pub transfer: Option, @@ -30,6 +32,7 @@ pub struct Subcall { pub context: Context, } +#[derive(Debug, Clone)] pub struct SubcallOutput { pub reason: ExitReason, pub output: Vec, @@ -37,6 +40,35 @@ pub struct SubcallOutput { pub logs: Vec, } +impl SubcallOutput { + pub fn revert() -> Self { + Self { + reason: ExitReason::Revert(ExitRevert::Reverted), + output: Vec::new(), + cost: 0, + logs: Vec::new(), + } + } + + pub fn succeed() -> Self { + Self { + reason: ExitReason::Succeed(ExitSucceed::Returned), + output: Vec::new(), + cost: 0, + logs: Vec::new(), + } + } + + pub fn out_of_gas() -> Self { + Self { + reason: ExitReason::Error(ExitError::OutOfGas), + output: Vec::new(), + cost: 0, + logs: Vec::new(), + } + } +} + pub trait SubcallTrait: FnMut(Subcall) -> SubcallOutput + 'static {} impl SubcallOutput + 'static> SubcallTrait for T {} @@ -83,7 +115,7 @@ impl PrecompileHandle for MockHandle { context: &Context, ) -> (ExitReason, Vec) { if self - .record_cost(crate::costs::call_cost( + .record_cost(crate::evm::costs::call_cost( context.apparent_value, &evm::Config::london(), )) diff --git a/precompiles/utils/src/testing/mod.rs b/precompiles/utils/src/testing/mod.rs index e247b3a943..89a10b6438 100644 --- a/precompiles/utils/src/testing/mod.rs +++ b/precompiles/utils/src/testing/mod.rs @@ -18,9 +18,15 @@ pub mod account; pub mod execution; pub mod handle; pub mod modifier; -pub mod solidity; +mod solidity; -pub use {account::*, execution::*, handle::*, modifier::*}; +pub use { + account::*, + execution::*, + handle::*, + modifier::*, + solidity::{check_precompile_implements_solidity_interfaces, compute_selector}, +}; use fp_evm::Log; diff --git a/precompiles/utils/src/testing/modifier.rs b/precompiles/utils/src/testing/modifier.rs index bd5794be4f..41e3c56feb 100644 --- a/precompiles/utils/src/testing/modifier.rs +++ b/precompiles/utils/src/testing/modifier.rs @@ -16,8 +16,8 @@ use { crate::{ + solidity::codec::Writer, testing::{decode_revert_message, MockHandle}, - EvmDataWriter, }, fp_evm::{Context, PrecompileFailure, PrecompileSet}, sp_core::{H160, U256}, @@ -53,7 +53,7 @@ impl PrecompilesModifierTester

{ let handle = &mut self.handle; handle.is_static = true; handle.context.apparent_value = U256::zero(); - handle.input = EvmDataWriter::new_with_selector(selector).build(); + handle.input = Writer::new_with_selector(selector).build(); let res = self.precompiles.execute(handle); @@ -73,7 +73,7 @@ impl PrecompilesModifierTester

{ let handle = &mut self.handle; handle.is_static = false; handle.context.apparent_value = U256::one(); - handle.input = EvmDataWriter::new_with_selector(selector).build(); + handle.input = Writer::new_with_selector(selector).build(); let res = self.precompiles.execute(handle); diff --git a/precompiles/utils/src/testing/solidity.rs b/precompiles/utils/src/testing/solidity.rs index 2bf9367fc1..fb3e24dd7a 100644 --- a/precompiles/utils/src/testing/solidity.rs +++ b/precompiles/utils/src/testing/solidity.rs @@ -23,6 +23,34 @@ use std::{ io::{BufRead, BufReader, Read}, }; +pub fn check_precompile_implements_solidity_interfaces( + files: &[&'static str], + supports_selector: F, +) where + F: Fn(u32) -> bool, +{ + for file in files { + for solidity_fn in get_selectors(file) { + assert_eq!( + solidity_fn.compute_selector_hex(), + solidity_fn.docs_selector, + "documented selector for '{}' did not match in file '{}'", + solidity_fn.signature(), + file, + ); + + let selector = solidity_fn.compute_selector(); + if !supports_selector(selector) { + panic!( + "precompile don't support selector {selector:x} for function '{}' listed in file\ + {file}", + solidity_fn.signature(), + ) + } + } + } +} + /// Represents a declared custom type struct within a solidity file #[derive(Clone, Default, Debug)] pub struct SolidityStruct { diff --git a/precompiles/utils/src/tests.rs b/precompiles/utils/src/tests.rs index 7a9aa56157..8f0739358a 100644 --- a/precompiles/utils/src/tests.rs +++ b/precompiles/utils/src/tests.rs @@ -16,12 +16,15 @@ use { crate::{ - data::{ - encode_as_function_return_value, - xcm::{network_id_from_bytes, network_id_to_bytes}, - }, prelude::*, - revert::Backtrace, + solidity::{ + codec::{ + xcm::{network_id_from_bytes, network_id_to_bytes}, + Reader, Writer, + }, + modifier::{check_function_modifier, FunctionModifier}, + revert::Backtrace, + }, }, frame_support::traits::ConstU32, hex_literal::hex, @@ -50,7 +53,7 @@ fn display_bytes(bytes: &[u8]) { fn write_bool() { let value = true; - let writer_output = EvmDataWriter::new().write(value).build(); + let writer_output = Writer::new().write(value).build(); let mut expected_output = [0u8; 32]; expected_output[31] = 1; @@ -62,9 +65,9 @@ fn write_bool() { fn read_bool() { let value = true; - let writer_output = EvmDataWriter::new().write(value).build(); + let writer_output = Writer::new().write(value).build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: bool = reader.read().expect("to correctly parse bool"); assert_eq!(value, parsed); @@ -74,7 +77,7 @@ fn read_bool() { fn write_u64() { let value = 42u64; - let writer_output = EvmDataWriter::new().write(value).build(); + let writer_output = Writer::new().write(value).build(); let mut expected_output = [0u8; 32]; expected_output[24..].copy_from_slice(&value.to_be_bytes()); @@ -85,9 +88,9 @@ fn write_u64() { #[test] fn read_u64() { let value = 42u64; - let writer_output = EvmDataWriter::new().write(value).build(); + let writer_output = Writer::new().write(value).build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: u64 = reader.read().expect("to correctly parse u64"); assert_eq!(value, parsed); @@ -97,7 +100,7 @@ fn read_u64() { fn write_u128() { let value = 42u128; - let writer_output = EvmDataWriter::new().write(value).build(); + let writer_output = Writer::new().write(value).build(); let mut expected_output = [0u8; 32]; expected_output[16..].copy_from_slice(&value.to_be_bytes()); @@ -108,9 +111,9 @@ fn write_u128() { #[test] fn read_u128() { let value = 42u128; - let writer_output = EvmDataWriter::new().write(value).build(); + let writer_output = Writer::new().write(value).build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: u128 = reader.read().expect("to correctly parse u128"); assert_eq!(value, parsed); @@ -120,7 +123,7 @@ fn read_u128() { fn write_u256() { let value = U256::from(42); - let writer_output = EvmDataWriter::new().write(value).build(); + let writer_output = Writer::new().write(value).build(); let mut expected_output = [0u8; 32]; value.to_big_endian(&mut expected_output); @@ -131,40 +134,21 @@ fn write_u256() { #[test] fn read_u256() { let value = U256::from(42); - let writer_output = EvmDataWriter::new().write(value).build(); + let writer_output = Writer::new().write(value).build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: U256 = reader.read().expect("to correctly parse U256"); assert_eq!(value, parsed); } -#[test] -fn read_selector() { - use sha3::{Digest, Keccak256}; - - #[precompile_utils_macro::generate_function_selector] - #[derive(Debug, PartialEq)] - enum FakeAction { - Action1 = "action1()", - } - - let selector = &Keccak256::digest(b"action1()")[0..4]; - - let parsed_selector = - EvmDataReader::read_selector::(selector).expect("there is a selector"); - EvmDataReader::new_skip_selector(selector).expect("there is a selector"); - - assert_eq!(parsed_selector, FakeAction::Action1) -} - #[test] #[should_panic(expected = "to correctly parse U256")] fn read_u256_too_short() { let value = U256::from(42); - let writer_output = EvmDataWriter::new().write(value).build(); + let writer_output = Writer::new().write(value).build(); - let mut reader = EvmDataReader::new(&writer_output[0..31]); + let mut reader = Reader::new(&writer_output[0..31]); let _: U256 = reader.read().expect("to correctly parse U256"); } @@ -177,7 +161,7 @@ fn write_h256() { let value = H256::from(raw); - let output = EvmDataWriter::new().write(value).build(); + let output = Writer::new().write(value).build(); assert_eq!(&output, &raw); } @@ -195,9 +179,9 @@ fn read_h256() { raw[12] = 43; raw[31] = 44; let value = H256::from(raw); - let writer_output = EvmDataWriter::new().write(value).build(); + let writer_output = Writer::new().write(value).build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: H256 = reader.read().expect("to correctly parse H256"); assert_eq!(value, parsed); @@ -211,9 +195,9 @@ fn read_h256_too_short() { raw[12] = 43; raw[31] = 44; let value = H256::from(raw); - let writer_output = EvmDataWriter::new().write(value).build(); + let writer_output = Writer::new().write(value).build(); - let mut reader = EvmDataReader::new(&writer_output[0..31]); + let mut reader = Reader::new(&writer_output[0..31]); let _: H256 = reader.read().expect("to correctly parse H256"); } @@ -221,7 +205,7 @@ fn read_h256_too_short() { fn write_address() { let value = H160::repeat_byte(0xAA); - let output = EvmDataWriter::new().write(Address(value)).build(); + let output = Writer::new().write(Address(value)).build(); assert_eq!(output.len(), 32); assert_eq!(&output[12..32], value.as_bytes()); @@ -230,9 +214,9 @@ fn write_address() { #[test] fn read_address() { let value = H160::repeat_byte(0xAA); - let writer_output = EvmDataWriter::new().write(Address(value)).build(); + let writer_output = Writer::new().write(Address(value)).build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: Address = reader.read().expect("to correctly parse Address"); assert_eq!(value, parsed.0); @@ -247,11 +231,11 @@ fn write_h256_array() { H256::repeat_byte(0x44), H256::repeat_byte(0x55), ]; - let writer_output = EvmDataWriter::new().write(array.clone()).build(); + let writer_output = Writer::new().write(array.clone()).build(); assert_eq!(writer_output.len(), 0xE0); // We can read this "manualy" using simpler functions since arrays are 32-byte aligned. - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); assert_eq!(reader.read::().expect("read offset"), 32.into()); assert_eq!(reader.read::().expect("read size"), 5.into()); @@ -271,9 +255,9 @@ fn read_h256_array() { H256::repeat_byte(0x44), H256::repeat_byte(0x55), ]; - let writer_output = EvmDataWriter::new().write(array.clone()).build(); + let writer_output = Writer::new().write(array.clone()).build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: Vec = reader.read().expect("to correctly parse Vec"); assert_eq!(array, parsed); @@ -288,11 +272,11 @@ fn write_u256_array() { u256_repeat_byte(0x44), u256_repeat_byte(0x55), ]; - let writer_output = EvmDataWriter::new().write(array.clone()).build(); + let writer_output = Writer::new().write(array.clone()).build(); assert_eq!(writer_output.len(), 0xE0); // We can read this "manualy" using simpler functions since arrays are 32-byte aligned. - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); assert_eq!(reader.read::().expect("read offset"), 32.into()); assert_eq!(reader.read::().expect("read size"), 5.into()); @@ -312,9 +296,9 @@ fn read_u256_array() { u256_repeat_byte(0x44), u256_repeat_byte(0x55), ]; - let writer_output = EvmDataWriter::new().write(array.clone()).build(); + let writer_output = Writer::new().write(array.clone()).build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: Vec = reader.read().expect("to correctly parse Vec"); assert_eq!(array, parsed); @@ -329,10 +313,10 @@ fn write_address_array() { Address(H160::repeat_byte(0x44)), Address(H160::repeat_byte(0x55)), ]; - let writer_output = EvmDataWriter::new().write(array.clone()).build(); + let writer_output = Writer::new().write(array.clone()).build(); // We can read this "manualy" using simpler functions since arrays are 32-byte aligned. - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); assert_eq!(reader.read::().expect("read offset"), 32.into()); assert_eq!(reader.read::().expect("read size"), 5.into()); @@ -352,9 +336,9 @@ fn read_address_array() { Address(H160::repeat_byte(0x44)), Address(H160::repeat_byte(0x55)), ]; - let writer_output = EvmDataWriter::new().write(array.clone()).build(); + let writer_output = Writer::new().write(array.clone()).build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: Vec

= reader.read().expect("to correctly parse Vec"); assert_eq!(array, parsed); @@ -369,11 +353,11 @@ fn read_address_array_size_too_big() { Address(H160::repeat_byte(0x44)), Address(H160::repeat_byte(0x55)), ]; - let mut writer_output = EvmDataWriter::new().write(array).build(); + let mut writer_output = Writer::new().write(array).build(); U256::from(6u32).to_big_endian(&mut writer_output[0x20..0x40]); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); match reader.read::>().in_field("field") { Ok(_) => panic!("should not parse correctly"), @@ -399,11 +383,11 @@ fn write_address_nested_array() { Address(H160::repeat_byte(0x55)), ], ]; - let writer_output = EvmDataWriter::new().write(array.clone()).build(); + let writer_output = Writer::new().write(array.clone()).build(); assert_eq!(writer_output.len(), 0x160); // We can read this "manualy" using simpler functions since arrays are 32-byte aligned. - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); assert_eq!(reader.read::().expect("read offset"), 0x20.into()); // 0x00 assert_eq!(reader.read::().expect("read size"), 2.into()); // 0x20 @@ -431,9 +415,9 @@ fn read_address_nested_array() { Address(H160::repeat_byte(0x55)), ], ]; - let writer_output = EvmDataWriter::new().write(array.clone()).build(); + let writer_output = Writer::new().write(array.clone()).build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: Vec> = reader.read().expect("to correctly parse Vec>"); assert_eq!(array, parsed); @@ -450,7 +434,7 @@ fn write_multiple_arrays() { let array2 = vec![H256::repeat_byte(0x44), H256::repeat_byte(0x55)]; - let writer_output = EvmDataWriter::new() + let writer_output = Writer::new() .write(array1.clone()) .write(array2.clone()) .build(); @@ -458,7 +442,7 @@ fn write_multiple_arrays() { assert_eq!(writer_output.len(), 0x120); // We can read this "manualy" using simpler functions since arrays are 32-byte aligned. - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); assert_eq!(reader.read::().expect("read 1st offset"), 0x40.into()); // 0x00 assert_eq!(reader.read::().expect("read 2nd offset"), 0xc0.into()); // 0x20 @@ -481,7 +465,7 @@ fn read_multiple_arrays() { let array2 = vec![H256::repeat_byte(0x44), H256::repeat_byte(0x55)]; - let writer_output = EvmDataWriter::new() + let writer_output = Writer::new() .write(array1.clone()) .write(array2.clone()) .build(); @@ -494,7 +478,7 @@ fn read_multiple_arrays() { // 2 H256 0x120 assert_eq!(writer_output.len(), 0x120); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: Vec
= reader.read().expect("to correctly parse Vec
"); assert_eq!(array1, parsed); @@ -507,11 +491,9 @@ fn read_multiple_arrays() { fn read_bytes() { let data = b"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod\ tempor incididunt ut labore et dolore magna aliqua."; - let writer_output = EvmDataWriter::new() - .write(UnboundedBytes::from(&data[..])) - .build(); + let writer_output = Writer::new().write(UnboundedBytes::from(&data[..])).build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: UnboundedBytes = reader.read().expect("to correctly parse Bytes"); assert_eq!(data, parsed.as_bytes()); @@ -522,12 +504,10 @@ fn write_bytes() { let data = b"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod\ tempor incididunt ut labore et dolore magna aliqua."; - let writer_output = EvmDataWriter::new() - .write(UnboundedBytes::from(&data[..])) - .build(); + let writer_output = Writer::new().write(UnboundedBytes::from(&data[..])).build(); // We can read this "manualy" using simpler functions. - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); // We pad data to a multiple of 32 bytes. let mut padded = data.to_vec(); @@ -547,11 +527,9 @@ fn write_bytes() { fn read_string() { let data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod\ tempor incididunt ut labore et dolore magna aliqua."; - let writer_output = EvmDataWriter::new() - .write(UnboundedBytes::from(data)) - .build(); + let writer_output = Writer::new().write(UnboundedBytes::from(data)).build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: UnboundedBytes = reader.read().expect("to correctly parse Bytes"); assert_eq!(data, parsed.as_str().expect("valid utf8")); @@ -562,12 +540,10 @@ fn write_string() { let data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod\ tempor incididunt ut labore et dolore magna aliqua."; - let writer_output = EvmDataWriter::new() - .write(UnboundedBytes::from(data)) - .build(); + let writer_output = Writer::new().write(UnboundedBytes::from(data)).build(); // We can read this "manualy" using simpler functions. - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); // We pad data to next multiple of 32 bytes. let mut padded = data.as_bytes().to_vec(); @@ -588,7 +564,7 @@ fn write_vec_bytes() { let data = b"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod\ tempor incididunt ut labore et dolore magna aliqua."; - let writer_output = EvmDataWriter::new() + let writer_output = Writer::new() .write(vec![ UnboundedBytes::from(&data[..]), UnboundedBytes::from(&data[..]), @@ -605,7 +581,7 @@ fn write_vec_bytes() { assert!(data.len() < 0x80); padded.resize(0x80, 0); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); // Offset of vec assert_eq!(reader.read::().expect("read offset"), 32.into()); @@ -644,7 +620,7 @@ fn read_vec_of_bytes() { let data = b"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod\ tempor incididunt ut labore et dolore magna aliqua."; - let writer_output = EvmDataWriter::new() + let writer_output = Writer::new() .write(vec![ UnboundedBytes::from(&data[..]), UnboundedBytes::from(&data[..]), @@ -656,7 +632,7 @@ fn read_vec_of_bytes() { .map(|chunk| H256::from_slice(chunk)) .for_each(|hash| println!("{:?}", hash)); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: Vec = reader.read().expect("to correctly parse Vec"); assert_eq!( @@ -670,9 +646,9 @@ fn read_vec_of_bytes() { // The following test parses input data generated by web3 from a Solidity contract. // This is important to test on external data since all the above tests can only test consistency -// between `EvmDataReader` and `EvmDataWriter`. +// between `Reader` and `Writer`. // -// It also provides an example on how to impl `EvmData` for Solidity structs. +// It also provides an example on how to impl `solidity::Codec` for Solidity structs. // // struct MultiLocation { // uint8 parents; @@ -686,21 +662,16 @@ fn read_vec_of_bytes() { // uint64 weight // ) external; -#[derive(Clone, Debug, Eq, PartialEq, EvmData)] +#[derive(Clone, Debug, Eq, PartialEq, solidity::Codec)] struct MultiLocation { parents: u8, interior: Vec, } -#[generate_function_selector] -#[derive(Debug, PartialEq)] -pub enum Action { - TransferMultiAsset = "transfer_multiasset((uint8,bytes[]),uint256,(uint8,bytes[]),uint64)", -} - #[test] fn read_complex_solidity_function() { // Function call data generated by web3. + // transfer_multiasset((uint8,bytes[]),uint256,(uint8,bytes[]),uint64) let data = hex!( "b38c60fa 0000000000000000000000000000000000000000000000000000000000000080 @@ -725,10 +696,10 @@ fn read_complex_solidity_function() { 0100000000000000000000000000000000000000000000000000000000000000" ); - let selector = EvmDataReader::read_selector::(&data).expect("to read selector"); - let mut reader = EvmDataReader::new_skip_selector(&data).expect("to read selector"); + let selector = solidity::codec::selector(&data); + let mut reader = Reader::new_skip_selector(&data).expect("to read selector"); - assert_eq!(selector, Action::TransferMultiAsset); + assert_eq!(selector, Some(0xb38c60fa)); // asset assert_eq!( reader.read::().unwrap(), @@ -761,22 +732,22 @@ fn read_complex_solidity_function() { #[test] fn junctions_decoder_works() { - let writer_output = EvmDataWriter::new() + let writer_output = Writer::new() .write(Junctions::X1(Junction::OnlyChild)) .build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: Junctions = reader .read::() .expect("to correctly parse Junctions"); assert_eq!(parsed, Junctions::X1(Junction::OnlyChild)); - let writer_output = EvmDataWriter::new() + let writer_output = Writer::new() .write(Junctions::X2(Junction::OnlyChild, Junction::OnlyChild)) .build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: Junctions = reader .read::() .expect("to correctly parse Junctions"); @@ -786,7 +757,7 @@ fn junctions_decoder_works() { Junctions::X2(Junction::OnlyChild, Junction::OnlyChild) ); - let writer_output = EvmDataWriter::new() + let writer_output = Writer::new() .write(Junctions::X3( Junction::OnlyChild, Junction::OnlyChild, @@ -794,7 +765,7 @@ fn junctions_decoder_works() { )) .build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: Junctions = reader .read::() .expect("to correctly parse Junctions"); @@ -811,23 +782,23 @@ fn junctions_decoder_works() { #[test] fn junction_decoder_works() { - let writer_output = EvmDataWriter::new().write(Junction::Parachain(0)).build(); + let writer_output = Writer::new().write(Junction::Parachain(0)).build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: Junction = reader .read::() .expect("to correctly parse Junctions"); assert_eq!(parsed, Junction::Parachain(0)); - let writer_output = EvmDataWriter::new() + let writer_output = Writer::new() .write(Junction::AccountId32 { network: None, id: [1u8; 32], }) .build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: Junction = reader .read::() .expect("to correctly parse Junctions"); @@ -840,14 +811,14 @@ fn junction_decoder_works() { } ); - let writer_output = EvmDataWriter::new() + let writer_output = Writer::new() .write(Junction::AccountIndex64 { network: None, index: u64::from_be_bytes([1u8; 8]), }) .build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: Junction = reader .read::() .expect("to correctly parse Junctions"); @@ -860,14 +831,14 @@ fn junction_decoder_works() { } ); - let writer_output = EvmDataWriter::new() + let writer_output = Writer::new() .write(Junction::AccountKey20 { network: None, key: H160::repeat_byte(0xAA).as_bytes().try_into().unwrap(), }) .build(); - let mut reader = EvmDataReader::new(&writer_output); + let mut reader = Reader::new(&writer_output); let parsed: Junction = reader .read::() .expect("to correctly parse Junctions"); @@ -984,7 +955,7 @@ fn read_static_size_tuple() { 0000000000000000000000000000000000000000000000000000000000000001" ); - let mut reader = EvmDataReader::new(&data); + let mut reader = Reader::new(&data); assert_eq!( reader.read::<(Address, U256)>().unwrap(), @@ -1005,7 +976,7 @@ fn read_dynamic_size_tuple() { 0100000000000000000000000000000000000000000000000000000000000000" ); - let mut reader = EvmDataReader::new(&data); + let mut reader = Reader::new(&data); assert_eq!( reader.read::<(u8, Vec)>().unwrap(), @@ -1015,7 +986,7 @@ fn read_dynamic_size_tuple() { #[test] fn write_static_size_tuple() { - let output = EvmDataWriter::new() + let output = Writer::new() .write((Address(H160::repeat_byte(0x11)), U256::from(1u8))) .build(); @@ -1030,7 +1001,7 @@ fn write_static_size_tuple() { #[test] fn write_dynamic_size_tuple() { - let output = EvmDataWriter::new() + let output = Writer::new() .write((1u8, vec![UnboundedBytes::from(vec![0x01])])) .build(); @@ -1050,8 +1021,7 @@ fn write_dynamic_size_tuple() { #[test] fn write_static_size_tuple_in_return_position() { - let output = - encode_as_function_return_value((Address(H160::repeat_byte(0x11)), U256::from(1u8))); + let output = solidity::encode_return_value((Address(H160::repeat_byte(0x11)), U256::from(1u8))); // (address, uint256) encoded by web3 let data = hex!( @@ -1064,7 +1034,7 @@ fn write_static_size_tuple_in_return_position() { #[test] fn write_dynamic_size_tuple_in_return_position() { - let output = encode_as_function_return_value((1u8, vec![UnboundedBytes::from(vec![0x01])])); + let output = solidity::encode_return_value((1u8, vec![UnboundedBytes::from(vec![0x01])])); // (uint8, bytes[]) encoded by web3 let data = hex!( @@ -1109,42 +1079,43 @@ fn error_formatting() { #[test] fn evm_data_solidity_types() { + use crate::solidity::Codec; // Simple types - assert_eq!(bool::solidity_type(), "bool"); - assert_eq!(u8::solidity_type(), "uint8"); - assert_eq!(u16::solidity_type(), "uint16"); - assert_eq!(u32::solidity_type(), "uint32"); - assert_eq!(u64::solidity_type(), "uint64"); - assert_eq!(u128::solidity_type(), "uint128"); - assert_eq!(U256::solidity_type(), "uint256"); - assert_eq!(H256::solidity_type(), "bytes32"); - assert_eq!(Address::solidity_type(), "address"); - assert_eq!(UnboundedBytes::solidity_type(), "bytes"); - assert_eq!(BoundedBytes::>::solidity_type(), "bytes"); + assert_eq!(bool::signature(), "bool"); + assert_eq!(u8::signature(), "uint8"); + assert_eq!(u16::signature(), "uint16"); + assert_eq!(u32::signature(), "uint32"); + assert_eq!(u64::signature(), "uint64"); + assert_eq!(u128::signature(), "uint128"); + assert_eq!(U256::signature(), "uint256"); + assert_eq!(H256::signature(), "bytes32"); + assert_eq!(Address::signature(), "address"); + assert_eq!(UnboundedBytes::signature(), "bytes"); + assert_eq!(BoundedBytes::>::signature(), "bytes"); // Arrays - assert_eq!(Vec::::solidity_type(), "bool[]"); - assert_eq!(Vec::::solidity_type(), "uint8[]"); - assert_eq!(Vec::::solidity_type(), "uint16[]"); - assert_eq!(Vec::::solidity_type(), "uint32[]"); - assert_eq!(Vec::::solidity_type(), "uint64[]"); - assert_eq!(Vec::::solidity_type(), "uint128[]"); - assert_eq!(Vec::::solidity_type(), "uint256[]"); - assert_eq!(Vec::::solidity_type(), "bytes32[]"); - assert_eq!(Vec::
::solidity_type(), "address[]"); - assert_eq!(Vec::::solidity_type(), "bytes[]"); - assert_eq!(Vec::>>::solidity_type(), "bytes[]"); + assert_eq!(Vec::::signature(), "bool[]"); + assert_eq!(Vec::::signature(), "uint8[]"); + assert_eq!(Vec::::signature(), "uint16[]"); + assert_eq!(Vec::::signature(), "uint32[]"); + assert_eq!(Vec::::signature(), "uint64[]"); + assert_eq!(Vec::::signature(), "uint128[]"); + assert_eq!(Vec::::signature(), "uint256[]"); + assert_eq!(Vec::::signature(), "bytes32[]"); + assert_eq!(Vec::
::signature(), "address[]"); + assert_eq!(Vec::::signature(), "bytes[]"); + assert_eq!(Vec::>>::signature(), "bytes[]"); // Few tuples mixed with arrays - assert_eq!(<(bool, Address)>::solidity_type(), "(bool,address)"); - assert_eq!(<(Vec, Address)>::solidity_type(), "(bool[],address)"); - assert_eq!(<(bool, Vec
)>::solidity_type(), "(bool,address[])"); - assert_eq!(Vec::<(bool, Address)>::solidity_type(), "(bool,address)[]"); + assert_eq!(<(bool, Address)>::signature(), "(bool,address)"); + assert_eq!(<(Vec, Address)>::signature(), "(bool[],address)"); + assert_eq!(<(bool, Vec
)>::signature(), "(bool,address[])"); + assert_eq!(Vec::<(bool, Address)>::signature(), "(bool,address)[]"); assert_eq!( - Vec::<(bool, Vec
)>::solidity_type(), + Vec::<(bool, Vec
)>::signature(), "(bool,address[])[]" ); // Struct encode like tuples - assert_eq!(MultiLocation::solidity_type(), "(uint8,bytes[])"); + assert_eq!(MultiLocation::signature(), "(uint8,bytes[])"); } diff --git a/precompiles/utils/tests-external/lib.rs b/precompiles/utils/tests-external/lib.rs index a164f59bd5..1f2ff158be 100644 --- a/precompiles/utils/tests-external/lib.rs +++ b/precompiles/utils/tests-external/lib.rs @@ -24,7 +24,12 @@ mod tests { use frame_support::traits::Everything; use frame_support::{construct_runtime, parameter_types, weights::Weight}; use pallet_evm::{EnsureAddressNever, EnsureAddressRoot}; - use precompile_utils::{precompile_set::*, revert, testing::*, EvmDataWriter, EvmResult}; + use precompile_utils::{ + precompile_set::*, + solidity::{codec::Writer, revert::revert}, + testing::*, + EvmResult, + }; use sp_core::H160; use sp_core::{H256, U256}; use sp_runtime::{ @@ -113,7 +118,7 @@ mod tests { handle.code_address(), None, // calls subcallLayer2() - EvmDataWriter::new_with_selector(0x0b93381bu32).build(), + Writer::new_with_selector(0x0b93381bu32).build(), None, false, &Context { @@ -220,7 +225,7 @@ mod tests { precompiles() .prepare_test(Alice, H160::from_low_u64_be(1), PCall::success {}) .with_subcall_handle(|Subcall { .. }| panic!("there should be no subcall")) - .execute_returns_encoded(()) + .execute_returns(()) }) } @@ -274,7 +279,7 @@ mod tests { precompiles() .prepare_test(Alice, H160::from_low_u64_be(2), PCall::success {}) .with_subcall_handle(|Subcall { .. }| panic!("there should be no subcall")) - .execute_returns_encoded(()) + .execute_returns(()) }) } @@ -288,7 +293,7 @@ mod tests { PCall::success {}, ) .with_subcall_handle(|Subcall { .. }| panic!("there should be no subcall")) - .execute_returns_encoded(()) + .execute_returns(()) }) } @@ -302,14 +307,9 @@ mod tests { .prepare_test(Alice, H160::from_low_u64_be(4), PCall::subcall {}) .with_subcall_handle(move |Subcall { .. }| { *subcall_occured.borrow_mut() = true; - SubcallOutput { - reason: ExitReason::Succeed(evm::ExitSucceed::Returned), - output: vec![], - cost: 0, - logs: vec![], - } + SubcallOutput::succeed() }) - .execute_returns_encoded(()); + .execute_returns(()); } assert!(*subcall_occured.borrow()); }) diff --git a/precompiles/xcm-transactor/src/tests.rs b/precompiles/xcm-transactor/src/tests.rs index 25c83ebf07..c5641efc27 100644 --- a/precompiles/xcm-transactor/src/tests.rs +++ b/precompiles/xcm-transactor/src/tests.rs @@ -119,11 +119,7 @@ fn take_index_for_account() { .prepare_test(Alice, TransactorV1, input) .expect_cost(1) .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(Address(H160::from(Alice))) - .build(), - ); + .execute_returns(Address(H160::from(Alice))); }); } @@ -163,13 +159,7 @@ fn take_transact_info() { .prepare_test(Alice, TransactorV1, input) .expect_cost(2) .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(0u64) - .write(1u128) - .write(10000u64) - .build(), - ); + .execute_returns((0u64, 1u128, 10000u64)); }); } #[test] @@ -208,13 +198,7 @@ fn take_transact_info_with_signed() { .prepare_test(Alice, TransactorV1, input) .expect_cost(1) .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(0u64) - .write(1u128) - .write(10000u64) - .build(), - ); + .execute_returns((0u64, 1u128, 10_000u64)); }); } @@ -244,7 +228,7 @@ fn take_fee_per_second() { .prepare_test(Alice, TransactorV1, input) .expect_cost(1) .expect_no_logs() - .execute_returns_encoded(1u64); + .execute_returns(1u64); }); } @@ -284,7 +268,7 @@ fn test_transact_derivative_multilocation_v2() { ) .expect_cost(196892000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); }); } @@ -337,7 +321,7 @@ fn test_transact_derivative_multilocation() { ) .expect_cost(196892000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); }); } @@ -387,7 +371,7 @@ fn test_transact_derivative() { ) .expect_cost(196892001) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); }); } @@ -425,7 +409,7 @@ fn test_transact_derivative_v2() { ) .expect_cost(196892001) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); }); } @@ -470,7 +454,7 @@ fn test_transact_signed() { ) .expect_cost(476974001) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); }); } @@ -503,7 +487,7 @@ fn test_transact_signed_v2() { ) .expect_cost(476974001) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); }); } @@ -550,7 +534,7 @@ fn test_transact_signed_multilocation() { ) .expect_cost(476974000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); }); } @@ -585,58 +569,24 @@ fn test_transact_signed_multilocation_v2() { ) .expect_cost(476974000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); }); } #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented_v1() { - for file in ["src/v1/XcmTransactorV1.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCallV1::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces( + &["src/v1/XcmTransactorV1.sol"], + PCallV1::supports_selector, + ) } #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented_v2() { - for file in ["src/v2/XcmTransactorV2.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCallV2::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces( + &["src/v2/XcmTransactorV2.sol"], + PCallV2::supports_selector, + ) } #[test] @@ -651,7 +601,7 @@ fn test_deprecated_solidity_selectors_are_supported() { "transact_through_signed_multilocation((uint8,bytes[]),(uint8,bytes[]),uint64,bytes)", "transact_through_signed((uint8,bytes[]),address,uint64,bytes)", ] { - let selector = solidity::compute_selector(deprecated_function); + let selector = compute_selector(deprecated_function); if !PCallV1::supports_selector(selector) { panic!( "failed decoding selector 0x{:x} => '{}' as Action", diff --git a/precompiles/xcm-transactor/src/v2/mod.rs b/precompiles/xcm-transactor/src/v2/mod.rs index b063a4ba4f..6f3e89cfdb 100644 --- a/precompiles/xcm-transactor/src/v2/mod.rs +++ b/precompiles/xcm-transactor/src/v2/mod.rs @@ -79,7 +79,7 @@ where fee_asset: MultiLocation, weight: u64, inner_call: BoundedBytes, - fee_amount: SolidityConvert, + fee_amount: Convert, overall_weight: u64, ) -> EvmResult { XcmTransactorWrapper::::transact_through_derivative_multilocation_fee_weight( @@ -111,7 +111,7 @@ where fee_asset: Address, weight: u64, inner_call: BoundedBytes, - fee_amount: SolidityConvert, + fee_amount: Convert, overall_weight: u64, ) -> EvmResult { XcmTransactorWrapper::::transact_through_derivative_fee_weight( @@ -141,7 +141,7 @@ where fee_asset: MultiLocation, weight: u64, call: BoundedBytes, - fee_amount: SolidityConvert, + fee_amount: Convert, overall_weight: u64, ) -> EvmResult { XcmTransactorWrapper::::transact_through_signed_multilocation_fee_weight( @@ -164,7 +164,7 @@ where fee_asset: Address, weight: u64, call: BoundedBytes, - fee_amount: SolidityConvert, + fee_amount: Convert, overall_weight: u64, ) -> EvmResult { XcmTransactorWrapper::::transact_through_signed_fee_weight( diff --git a/precompiles/xcm-utils/src/lib.rs b/precompiles/xcm-utils/src/lib.rs index 54326aa889..fbb96e7232 100644 --- a/precompiles/xcm-utils/src/lib.rs +++ b/precompiles/xcm-utils/src/lib.rs @@ -28,7 +28,7 @@ use frame_support::{ use pallet_evm::AddressMapping; use parity_scale_codec::DecodeLimit; use precompile_utils::precompile_set::SelectorFilter; -use precompile_utils::{data::String, prelude::*}; +use precompile_utils::prelude::*; use sp_core::{H160, U256}; use sp_std::boxed::Box; use sp_std::marker::PhantomData; diff --git a/precompiles/xcm-utils/src/tests.rs b/precompiles/xcm-utils/src/tests.rs index d0ddee3034..4a8d9d4829 100644 --- a/precompiles/xcm-utils/src/tests.rs +++ b/precompiles/xcm-utils/src/tests.rs @@ -59,11 +59,7 @@ fn test_get_account_parent() { .prepare_test(Alice, Precompile1, input) .expect_cost(1) .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(Address(expected_address)) - .build(), - ); + .execute_returns(Address(expected_address)); }); } @@ -83,11 +79,7 @@ fn test_get_account_sibling() { .prepare_test(Alice, Precompile1, input) .expect_cost(1) .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(Address(expected_address)) - .build(), - ); + .execute_returns(Address(expected_address)); }); } @@ -104,7 +96,7 @@ fn test_weight_message() { .prepare_test(Alice, Precompile1, input) .expect_cost(0) .expect_no_logs() - .execute_returns_encoded(1000u64); + .execute_returns(1000u64); }); } @@ -119,7 +111,7 @@ fn test_get_units_per_second() { .prepare_test(Alice, Precompile1, input) .expect_cost(1) .expect_no_logs() - .execute_returns_encoded(U256::from(1_000_000_000_000u128)); + .execute_returns(U256::from(1_000_000_000_000u128)); }); } @@ -137,7 +129,7 @@ fn test_executor_clear_origin() { .prepare_test(Alice, Precompile1, input) .expect_cost(100001001) .expect_no_logs() - .execute_returns(EvmDataWriter::new().build()); + .execute_returns(()); }) } @@ -164,7 +156,7 @@ fn test_executor_send() { .prepare_test(Alice, Precompile1, input) .expect_cost(100002001) .expect_no_logs() - .execute_returns(EvmDataWriter::new().build()); + .execute_returns(()); let sent_messages = sent_xcm(); let (_, sent_message) = sent_messages.first().unwrap(); @@ -208,7 +200,7 @@ fn test_executor_transact() { .prepare_test(CryptoAlith, Precompile1, input) .expect_cost(1100001001) .expect_no_logs() - .execute_returns(EvmDataWriter::new().build()); + .execute_returns(()); // Transact executed let baltathar_account: AccountId = CryptoBaltathar.into(); @@ -231,7 +223,7 @@ fn test_send_clear_origin() { // Fixed: TestWeightInfo + (BaseXcmWeight * MessageLen) .expect_cost(100001000) .expect_no_logs() - .execute_returns(EvmDataWriter::new().build()); + .execute_returns(()); let sent_messages = sent_xcm(); let (_, sent_message) = sent_messages.first().unwrap(); @@ -267,25 +259,5 @@ fn execute_fails_if_called_by_smart_contract() { #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { - for file in ["XcmUtils.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCall::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces(&["XcmUtils.sol"], PCall::supports_selector) } diff --git a/precompiles/xtokens/Cargo.toml b/precompiles/xtokens/Cargo.toml index f2948a7208..e90c11ebe2 100644 --- a/precompiles/xtokens/Cargo.toml +++ b/precompiles/xtokens/Cargo.toml @@ -11,7 +11,7 @@ num_enum = { workspace = true } rustc-hex = { workspace = true } # Moonbeam -precompile-utils = { workspace = true } +precompile-utils = { workspace = true, features = [ "codec-xcm" ] } xcm-primitives = { workspace = true } # Substrate diff --git a/precompiles/xtokens/src/lib.rs b/precompiles/xtokens/src/lib.rs index 5a68a74f9e..51c4d1a187 100644 --- a/precompiles/xtokens/src/lib.rs +++ b/precompiles/xtokens/src/lib.rs @@ -24,7 +24,7 @@ use frame_support::{ traits::Get, }; use pallet_evm::AddressMapping; -use precompile_utils::{data::String, prelude::*}; +use precompile_utils::prelude::*; use sp_core::{H160, U256}; use sp_std::{ boxed::Box, @@ -70,7 +70,7 @@ where Runtime::RuntimeCall: Dispatchable + GetDispatchInfo, Runtime::RuntimeCall: From>, ::RuntimeOrigin: From>, - XBalanceOf: TryFrom + Into + EvmData, + XBalanceOf: TryFrom + Into + solidity::Codec, Runtime: AccountIdToCurrencyId>, { #[precompile::public("transfer(address,uint256,(uint8,bytes[]),uint64)")] @@ -323,7 +323,7 @@ where } // Currency -#[derive(EvmData)] +#[derive(solidity::Codec)] pub struct Currency { address: Address, amount: U256, @@ -338,7 +338,7 @@ impl From<(Address, U256)> for Currency { } } -#[derive(EvmData)] +#[derive(solidity::Codec)] pub struct EvmMultiAsset { location: MultiLocation, amount: U256, diff --git a/precompiles/xtokens/src/tests.rs b/precompiles/xtokens/src/tests.rs index 3a73fa0cf7..7d6bf67c7f 100644 --- a/precompiles/xtokens/src/tests.rs +++ b/precompiles/xtokens/src/tests.rs @@ -98,7 +98,7 @@ fn transfer_self_reserve_works() { ) .expect_cost(2000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); let expected_asset: MultiAsset = MultiAsset { id: AssetId::Concrete( @@ -145,7 +145,7 @@ fn transfer_to_reserve_works() { ) .expect_cost(3000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); let expected_asset: MultiAsset = MultiAsset { id: AssetId::Concrete( @@ -194,7 +194,7 @@ fn transfer_to_reserve_with_fee_works() { ) .expect_cost(3000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); let expected_asset: MultiAsset = MultiAsset { id: AssetId::Concrete( @@ -249,7 +249,7 @@ fn transfer_non_reserve_to_non_reserve_works() { ) .expect_cost(3000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); let expected_asset: MultiAsset = MultiAsset { id: AssetId::Concrete( @@ -298,7 +298,7 @@ fn transfer_non_reserve_to_non_reserve_with_fee_works() { ) .expect_cost(3000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); let expected_asset: MultiAsset = MultiAsset { id: AssetId::Concrete( @@ -353,7 +353,7 @@ fn transfer_multi_asset_to_reserve_works() { ) .expect_cost(3000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); let expected_asset: MultiAsset = MultiAsset { id: AssetId::Concrete(asset), @@ -401,7 +401,7 @@ fn transfer_multi_asset_self_reserve_works() { ) .expect_cost(2000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); let expected_asset: MultiAsset = MultiAsset { id: AssetId::Concrete(self_reserve), @@ -449,7 +449,7 @@ fn transfer_multi_asset_self_reserve_with_fee_works() { ) .expect_cost(2000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); let expected_asset: MultiAsset = MultiAsset { id: AssetId::Concrete(self_reserve.clone()), @@ -503,7 +503,7 @@ fn transfer_multi_asset_non_reserve_to_non_reserve() { ) .expect_cost(3000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); let expected_asset: MultiAsset = MultiAsset { id: AssetId::Concrete(asset_location), @@ -554,7 +554,7 @@ fn transfer_multi_asset_non_reserve_to_non_reserve_with_fee() { ) .expect_cost(3000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); let expected_asset: MultiAsset = MultiAsset { id: AssetId::Concrete(asset_location.clone()), @@ -608,7 +608,7 @@ fn transfer_multi_currencies() { ) .expect_cost(3000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); let expected_asset_1: MultiAsset = MultiAsset { id: AssetId::Concrete( @@ -685,7 +685,7 @@ fn transfer_multi_assets() { ) .expect_cost(3000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); let expected: crate::mock::RuntimeEvent = XtokensEvent::TransferredMultiAssets { sender: Alice.into(), @@ -841,27 +841,7 @@ fn transfer_multi_assets_is_not_sorted_error() { #[test] fn test_solidity_interface_has_all_function_selectors_documented_and_implemented() { - for file in ["Xtokens.sol"] { - for solidity_fn in solidity::get_selectors(file) { - assert_eq!( - solidity_fn.compute_selector_hex(), - solidity_fn.docs_selector, - "documented selector for '{}' did not match for file '{}'", - solidity_fn.signature(), - file, - ); - - let selector = solidity_fn.compute_selector(); - if !PCall::supports_selector(selector) { - panic!( - "failed decoding selector 0x{:x} => '{}' as Action for file '{}'", - selector, - solidity_fn.signature(), - file, - ) - } - } - } + check_precompile_implements_solidity_interfaces(&["Xtokens.sol"], PCall::supports_selector) } #[test] @@ -873,7 +853,7 @@ fn test_deprecated_solidity_selectors_are_supported() { "transfer_multi_currencies((address,uint256)[],uint32,(uint8,bytes[]),uint64)", "transfer_multi_assets(((uint8,bytes[]),uint256)[],uint32,(uint8,bytes[]),uint64)", ] { - let selector = solidity::compute_selector(deprecated_function); + let selector = compute_selector(deprecated_function); if !PCall::supports_selector(selector) { panic!( "failed decoding selector 0x{:x} => '{}' as Action", diff --git a/runtime/common/src/impl_xcm_evm_runner.rs b/runtime/common/src/impl_xcm_evm_runner.rs index 7cecb98294..a31657f550 100644 --- a/runtime/common/src/impl_xcm_evm_runner.rs +++ b/runtime/common/src/impl_xcm_evm_runner.rs @@ -20,7 +20,7 @@ macro_rules! impl_evm_runner_precompile_or_eth_xcm { use fp_evm::{CallInfo, CallOrCreateInfo, Context, Transfer}; use frame_support::dispatch::CallableCallFor; use pallet_evm::{Runner, RunnerError}; - use precompile_utils::prelude::*; + use precompile_utils::{prelude::*, evm::handle::with_precompile_handle}; use sp_core::U256; use sp_runtime::DispatchError; use sp_std::vec::Vec; diff --git a/runtime/moonbase/src/governance/origins.rs b/runtime/moonbase/src/governance/origins.rs index 738f306707..20d0829f1f 100644 --- a/runtime/moonbase/src/governance/origins.rs +++ b/runtime/moonbase/src/governance/origins.rs @@ -11,8 +11,6 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. -#![cfg_attr(not(feature = "std"), no_std)] - //! Custom origins for governance interventions. pub use custom_origins::*; diff --git a/runtime/moonbase/tests/integration_test.rs b/runtime/moonbase/tests/integration_test.rs index 34fb154bf6..95d9a92efd 100644 --- a/runtime/moonbase/tests/integration_test.rs +++ b/runtime/moonbase/tests/integration_test.rs @@ -66,7 +66,7 @@ use pallet_transaction_payment::Multiplier; use pallet_xcm_transactor::{Currency, CurrencyPayment, HrmpOperation, TransactWeights}; use parity_scale_codec::Encode; use sha3::{Digest, Keccak256}; -use sp_core::{crypto::UncheckedFrom, ByteArray, Pair, H160, U256}; +use sp_core::{crypto::UncheckedFrom, ByteArray, Pair, H160, H256, U256}; use sp_runtime::{traits::Convert, DispatchError, ModuleError, TokenError}; use xcm::latest::prelude::*; @@ -1141,7 +1141,7 @@ fn is_contributor_via_precompile() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(false); + .execute_returns(false); // Assert precompile reports Charlie is a nominator Precompiles::new() @@ -1154,7 +1154,7 @@ fn is_contributor_via_precompile() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); }) } @@ -1226,12 +1226,7 @@ fn reward_info_via_precompile() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(expected_total) - .write(expected_claimed) - .build(), - ); + .execute_returns((expected_total, expected_claimed)); }) } @@ -1395,7 +1390,7 @@ fn asset_erc20_precompiles_supply_and_balance() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(1000 * UNIT)); + .execute_returns(U256::from(1000 * UNIT)); // Access balanceOf through precompile Precompiles::new() @@ -1408,7 +1403,7 @@ fn asset_erc20_precompiles_supply_and_balance() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(1000 * UNIT)); + .execute_returns(U256::from(1000 * UNIT)); }); } @@ -1445,9 +1440,9 @@ fn asset_erc20_precompiles_transfer() { SELECTOR_LOG_TRANSFER, H160::from(ALICE), H160::from(BOB), - EvmDataWriter::new().write(U256::from(400 * UNIT)).build(), + solidity::encode_event_data(U256::from(400 * UNIT)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Make sure BOB has 400 UNIT Precompiles::new() @@ -1460,7 +1455,7 @@ fn asset_erc20_precompiles_transfer() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(400 * UNIT)); + .execute_returns(U256::from(400 * UNIT)); }); } @@ -1497,9 +1492,9 @@ fn asset_erc20_precompiles_approve() { SELECTOR_LOG_APPROVAL, H160::from(ALICE), H160::from(BOB), - EvmDataWriter::new().write(U256::from(400 * UNIT)).build(), + solidity::encode_event_data(U256::from(400 * UNIT)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Transfer tokens from Alice to Charlie by using BOB as origin Precompiles::new() @@ -1518,9 +1513,9 @@ fn asset_erc20_precompiles_approve() { SELECTOR_LOG_TRANSFER, H160::from(ALICE), H160::from(CHARLIE), - EvmDataWriter::new().write(U256::from(400 * UNIT)).build(), + solidity::encode_event_data(U256::from(400 * UNIT)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Make sure CHARLIE has 400 UNIT Precompiles::new() @@ -1533,7 +1528,7 @@ fn asset_erc20_precompiles_approve() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(400 * UNIT)); + .execute_returns(U256::from(400 * UNIT)); }); } @@ -1570,9 +1565,9 @@ fn asset_erc20_precompiles_mint_burn() { SELECTOR_LOG_TRANSFER, H160::default(), H160::from(BOB), - EvmDataWriter::new().write(U256::from(1000 * UNIT)).build(), + solidity::encode_event_data(U256::from(1_000 * UNIT)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Assert the asset has been minted assert_eq!(LocalAssets::total_supply(0u128), 2_000 * UNIT); @@ -1597,9 +1592,9 @@ fn asset_erc20_precompiles_mint_burn() { SELECTOR_LOG_TRANSFER, H160::from(BOB), H160::default(), - EvmDataWriter::new().write(U256::from(500 * UNIT)).build(), + solidity::encode_event_data(U256::from(500 * UNIT)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Assert the asset has been burnt assert_eq!(LocalAssets::total_supply(0u128), 1_500 * UNIT); @@ -1638,7 +1633,7 @@ fn asset_erc20_precompiles_freeze_thaw_account() { ) .expect_cost(6699) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); // Assert account is frozen assert_eq!( @@ -1657,7 +1652,7 @@ fn asset_erc20_precompiles_freeze_thaw_account() { ) .expect_cost(6713) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); // Assert account is not frozen assert!(LocalAssets::can_withdraw(0u128, &AccountId::from(ALICE), 1) @@ -1692,7 +1687,7 @@ fn asset_erc20_precompiles_freeze_thaw_asset() { ) .expect_cost(5548) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); // Assert account is frozen assert_eq!( @@ -1709,7 +1704,7 @@ fn asset_erc20_precompiles_freeze_thaw_asset() { ) .expect_cost(5550) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); }); } @@ -1741,7 +1736,7 @@ fn asset_erc20_precompiles_freeze_transfer_ownership() { ) .expect_cost(6614) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); }); } @@ -1775,7 +1770,7 @@ fn asset_erc20_precompiles_freeze_set_team() { ) .expect_cost(5577) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); // Bob should be able to mint, freeze, and thaw assert_ok!(LocalAssets::mint( @@ -1838,7 +1833,7 @@ fn xcm_asset_erc20_precompiles_supply_and_balance() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(1000 * UNIT)); + .execute_returns(U256::from(1000 * UNIT)); // Access balanceOf through precompile Precompiles::new() @@ -1851,7 +1846,7 @@ fn xcm_asset_erc20_precompiles_supply_and_balance() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(1000 * UNIT)); + .execute_returns(U256::from(1000 * UNIT)); }); } @@ -1900,9 +1895,9 @@ fn xcm_asset_erc20_precompiles_transfer() { SELECTOR_LOG_TRANSFER, H160::from(ALICE), H160::from(BOB), - EvmDataWriter::new().write(U256::from(400 * UNIT)).build(), + solidity::encode_event_data(U256::from(400 * UNIT)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Make sure BOB has 400 UNIT Precompiles::new() @@ -1915,7 +1910,7 @@ fn xcm_asset_erc20_precompiles_transfer() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(400 * UNIT)); + .execute_returns(U256::from(400 * UNIT)); }); } @@ -1964,9 +1959,9 @@ fn xcm_asset_erc20_precompiles_approve() { SELECTOR_LOG_APPROVAL, H160::from(ALICE), H160::from(BOB), - EvmDataWriter::new().write(U256::from(400 * UNIT)).build(), + solidity::encode_event_data(U256::from(400 * UNIT)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Transfer tokens from Alice to Charlie by using BOB as origin Precompiles::new() @@ -1985,9 +1980,9 @@ fn xcm_asset_erc20_precompiles_approve() { SELECTOR_LOG_TRANSFER, H160::from(ALICE), H160::from(CHARLIE), - EvmDataWriter::new().write(U256::from(400 * UNIT)).build(), + solidity::encode_event_data(U256::from(400 * UNIT)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Make sure CHARLIE has 400 UNIT Precompiles::new() @@ -2000,7 +1995,7 @@ fn xcm_asset_erc20_precompiles_approve() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(400 * UNIT)); + .execute_returns(U256::from(400 * UNIT)); }); } @@ -2059,7 +2054,7 @@ fn xtokens_precompiles_transfer() { ) .expect_cost(52170) .expect_no_logs() - .execute_returns(vec![]) + .execute_returns(()) }) } @@ -2111,7 +2106,7 @@ fn xtokens_precompiles_transfer_multiasset() { ) .expect_cost(52170) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); }) } @@ -2153,7 +2148,7 @@ fn xtokens_precompiles_transfer_native() { ) .expect_cost(16000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); }) } @@ -2201,7 +2196,7 @@ fn xtokens_precompile_transfer_local_asset() { ) .expect_cost(16000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); }) } @@ -2731,7 +2726,7 @@ fn transact_through_signed_precompile_works_v1() { ) .expect_cost(19078) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); }); } @@ -2771,7 +2766,7 @@ fn transact_through_signed_precompile_works_v2() { ) .expect_cost(19078) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); }); } @@ -2853,7 +2848,7 @@ fn author_mapping_precompile_associate_update_and_clear() { ) .expect_cost(16030) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); let expected_associate_event = RuntimeEvent::AuthorMapping(pallet_author_mapping::Event::KeysRegistered { @@ -2875,7 +2870,7 @@ fn author_mapping_precompile_associate_update_and_clear() { ) .expect_cost(15659) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); let expected_update_event = RuntimeEvent::AuthorMapping(pallet_author_mapping::Event::KeysRotated { @@ -2896,7 +2891,7 @@ fn author_mapping_precompile_associate_update_and_clear() { ) .expect_cost(16215) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); let expected_clear_event = RuntimeEvent::AuthorMapping(pallet_author_mapping::Event::KeysRemoved { @@ -2930,16 +2925,16 @@ fn author_mapping_register_and_set_keys() { ALICE, author_mapping_precompile_address, AuthorMappingPCall::set_keys { - keys: EvmDataWriter::new() - .write(sp_core::H256::from([1u8; 32])) - .write(sp_core::H256::from([3u8; 32])) - .build() - .into(), + keys: solidity::encode_arguments(( + H256::from([1u8; 32]), + H256::from([3u8; 32]), + )) + .into(), }, ) .expect_cost(16815) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); let expected_associate_event = RuntimeEvent::AuthorMapping(pallet_author_mapping::Event::KeysRegistered { @@ -2955,16 +2950,16 @@ fn author_mapping_register_and_set_keys() { ALICE, author_mapping_precompile_address, AuthorMappingPCall::set_keys { - keys: EvmDataWriter::new() - .write(sp_core::H256::from([2u8; 32])) - .write(sp_core::H256::from([4u8; 32])) - .build() - .into(), + keys: solidity::encode_arguments(( + H256::from([2u8; 32]), + H256::from([4u8; 32]), + )) + .into(), }, ) .expect_cost(16815) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); let expected_update_event = RuntimeEvent::AuthorMapping(pallet_author_mapping::Event::KeysRotated { @@ -2995,11 +2990,7 @@ fn test_xcm_utils_ml_tp_account() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(Address(expected_address_parent)) - .build(), - ); + .execute_returns(Address(expected_address_parent)); let parachain_2000_multilocation = MultiLocation::new(1, X1(Parachain(2000))); let expected_address_parachain: H160 = @@ -3019,11 +3010,7 @@ fn test_xcm_utils_ml_tp_account() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(Address(expected_address_parachain)) - .build(), - ); + .execute_returns(Address(expected_address_parachain)); let alice_in_parachain_2000_multilocation = MultiLocation::new( 1, @@ -3050,11 +3037,7 @@ fn test_xcm_utils_ml_tp_account() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(Address(expected_address_alice_in_parachain_2000)) - .build(), - ); + .execute_returns(Address(expected_address_alice_in_parachain_2000)); }); } @@ -3075,7 +3058,7 @@ fn test_xcm_utils_weight_message() { .prepare_test(ALICE, xcm_utils_precompile_address, input) .expect_cost(0) .expect_no_logs() - .execute_returns(EvmDataWriter::new().write(expected_weight).build()); + .execute_returns(expected_weight); }); } @@ -3094,7 +3077,7 @@ fn test_xcm_utils_get_units_per_second() { .prepare_test(ALICE, xcm_utils_precompile_address, input) .expect_cost(1000) .expect_no_logs() - .execute_returns(EvmDataWriter::new().write(expected_units).build()); + .execute_returns(expected_units); }); } diff --git a/runtime/moonbeam/tests/integration_test.rs b/runtime/moonbeam/tests/integration_test.rs index 0ff1d35c24..cd3e8481e1 100644 --- a/runtime/moonbeam/tests/integration_test.rs +++ b/runtime/moonbeam/tests/integration_test.rs @@ -1022,7 +1022,7 @@ fn is_contributor_via_precompile() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(false); + .execute_returns(false); // Assert precompile reports Charlie is a nominator Precompiles::new() @@ -1035,7 +1035,7 @@ fn is_contributor_via_precompile() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); }) } @@ -1107,12 +1107,7 @@ fn reward_info_via_precompile() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(expected_total) - .write(expected_claimed) - .build(), - ); + .execute_returns((expected_total, expected_claimed)); }) } @@ -1652,7 +1647,7 @@ fn asset_erc20_precompiles_supply_and_balance() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(1000 * GLMR)); + .execute_returns(U256::from(1000 * GLMR)); // Access balanceOf through precompile Precompiles::new() @@ -1665,7 +1660,7 @@ fn asset_erc20_precompiles_supply_and_balance() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(1000 * GLMR)); + .execute_returns(U256::from(1000 * GLMR)); }); } @@ -1702,9 +1697,9 @@ fn asset_erc20_precompiles_transfer() { SELECTOR_LOG_TRANSFER, H160::from(ALICE), H160::from(BOB), - EvmDataWriter::new().write(U256::from(400 * GLMR)).build(), + solidity::encode_event_data(U256::from(400 * GLMR)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Make sure BOB has 400 GLMR Precompiles::new() @@ -1717,7 +1712,7 @@ fn asset_erc20_precompiles_transfer() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(400 * GLMR)); + .execute_returns(U256::from(400 * GLMR)); }); } @@ -1754,9 +1749,9 @@ fn asset_erc20_precompiles_approve() { SELECTOR_LOG_APPROVAL, H160::from(ALICE), H160::from(BOB), - EvmDataWriter::new().write(U256::from(400 * GLMR)).build(), + solidity::encode_event_data(U256::from(400 * GLMR)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Transfer tokens from Alice to Charlie by using BOB as origin Precompiles::new() @@ -1775,9 +1770,9 @@ fn asset_erc20_precompiles_approve() { SELECTOR_LOG_TRANSFER, H160::from(ALICE), H160::from(CHARLIE), - EvmDataWriter::new().write(U256::from(400 * GLMR)).build(), + solidity::encode_event_data(U256::from(400 * GLMR)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Make sure CHARLIE has 400 GLMR Precompiles::new() @@ -1790,7 +1785,7 @@ fn asset_erc20_precompiles_approve() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(400 * GLMR)); + .execute_returns(U256::from(400 * GLMR)); }); } @@ -1827,9 +1822,9 @@ fn asset_erc20_precompiles_mint_burn() { SELECTOR_LOG_TRANSFER, H160::default(), H160::from(BOB), - EvmDataWriter::new().write(U256::from(1000 * GLMR)).build(), + solidity::encode_event_data(U256::from(1_000 * GLMR)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Assert the asset has been minted assert_eq!(LocalAssets::total_supply(0u128), 2_000 * GLMR); @@ -1854,9 +1849,9 @@ fn asset_erc20_precompiles_mint_burn() { SELECTOR_LOG_TRANSFER, H160::from(BOB), H160::default(), - EvmDataWriter::new().write(U256::from(500 * GLMR)).build(), + solidity::encode_event_data(U256::from(500 * GLMR)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Assert the asset has been burnt assert_eq!(LocalAssets::total_supply(0u128), 1_500 * GLMR); @@ -1895,7 +1890,7 @@ fn asset_erc20_precompiles_freeze_thaw_account() { ) .expect_cost(6699) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); // Assert account is frozen assert_eq!( @@ -1914,7 +1909,7 @@ fn asset_erc20_precompiles_freeze_thaw_account() { ) .expect_cost(6713) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); // Assert account is not frozen assert!(LocalAssets::can_withdraw(0u128, &AccountId::from(ALICE), 1) @@ -1949,7 +1944,7 @@ fn asset_erc20_precompiles_freeze_thaw_asset() { ) .expect_cost(5548) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); // Assert account is frozen assert_eq!( @@ -1966,7 +1961,7 @@ fn asset_erc20_precompiles_freeze_thaw_asset() { ) .expect_cost(5550) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); // Assert account is not frozen assert!(LocalAssets::can_withdraw(0u128, &AccountId::from(ALICE), 1) @@ -2003,7 +1998,7 @@ fn asset_erc20_precompiles_freeze_transfer_ownership() { ) .expect_cost(6614) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); // No clear way of testing BOB is new owner, other than doing a priviledged function // e.g., transfer_ownership again @@ -2045,7 +2040,7 @@ fn asset_erc20_precompiles_freeze_set_team() { ) .expect_cost(5577) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); // Bob should be able to mint, freeze, and thaw assert_ok!(LocalAssets::mint( @@ -2109,7 +2104,7 @@ fn xcm_asset_erc20_precompiles_supply_and_balance() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(1000 * GLMR)); + .execute_returns(U256::from(1000 * GLMR)); // Access balanceOf through precompile Precompiles::new() @@ -2122,7 +2117,7 @@ fn xcm_asset_erc20_precompiles_supply_and_balance() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(1000 * GLMR)); + .execute_returns(U256::from(1000 * GLMR)); }); } @@ -2172,9 +2167,9 @@ fn xcm_asset_erc20_precompiles_transfer() { SELECTOR_LOG_TRANSFER, H160::from(ALICE), H160::from(BOB), - EvmDataWriter::new().write(U256::from(400 * GLMR)).build(), + solidity::encode_event_data(U256::from(400 * GLMR)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Make sure BOB has 400 GLMR Precompiles::new() @@ -2187,7 +2182,7 @@ fn xcm_asset_erc20_precompiles_transfer() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(400 * GLMR)); + .execute_returns(U256::from(400 * GLMR)); }); } @@ -2237,9 +2232,9 @@ fn xcm_asset_erc20_precompiles_approve() { SELECTOR_LOG_APPROVAL, H160::from(ALICE), H160::from(BOB), - EvmDataWriter::new().write(U256::from(400 * GLMR)).build(), + solidity::encode_event_data(U256::from(400 * GLMR)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Transfer tokens from Alice to Charlie by using BOB as origin Precompiles::new() @@ -2258,9 +2253,9 @@ fn xcm_asset_erc20_precompiles_approve() { SELECTOR_LOG_TRANSFER, H160::from(ALICE), H160::from(CHARLIE), - EvmDataWriter::new().write(U256::from(400 * GLMR)).build(), + solidity::encode_event_data(U256::from(400 * GLMR)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Make sure CHARLIE has 400 GLMR Precompiles::new() @@ -2273,7 +2268,7 @@ fn xcm_asset_erc20_precompiles_approve() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(400 * GLMR)); + .execute_returns(U256::from(400 * GLMR)); }); } @@ -2333,7 +2328,7 @@ fn xtokens_precompile_transfer() { ) .expect_cost(24000) .expect_no_logs() - .execute_returns(vec![]) + .execute_returns(()) }) } @@ -2385,7 +2380,7 @@ fn xtokens_precompile_transfer_multiasset() { ) .expect_cost(24000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); }) } @@ -2533,7 +2528,7 @@ fn transact_through_signed_precompile_works_v2() { ) .expect_cost(19078) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); }); } @@ -2734,11 +2729,7 @@ fn test_xcm_utils_ml_to_account() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(Address(expected_address_parent)) - .build(), - ); + .execute_returns(Address(expected_address_parent)); let parachain_2000_multilocation = MultiLocation::new(1, X1(Parachain(2000))); let expected_address_parachain: H160 = @@ -2758,11 +2749,7 @@ fn test_xcm_utils_ml_to_account() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(Address(expected_address_parachain)) - .build(), - ); + .execute_returns(Address(expected_address_parachain)); let alice_in_parachain_2000_multilocation = MultiLocation::new( 1, @@ -2806,7 +2793,7 @@ fn test_xcm_utils_weight_message() { .prepare_test(ALICE, xcm_utils_precompile_address, input) .expect_cost(0) .expect_no_logs() - .execute_returns(EvmDataWriter::new().write(expected_weight).build()); + .execute_returns(expected_weight); }); } @@ -2825,7 +2812,7 @@ fn test_xcm_utils_get_units_per_second() { .prepare_test(ALICE, xcm_utils_precompile_address, input) .expect_cost(1000) .expect_no_logs() - .execute_returns(EvmDataWriter::new().write(expected_units).build()); + .execute_returns(expected_units); }); } diff --git a/runtime/moonriver/tests/integration_test.rs b/runtime/moonriver/tests/integration_test.rs index c75f1712da..5df0f90644 100644 --- a/runtime/moonriver/tests/integration_test.rs +++ b/runtime/moonriver/tests/integration_test.rs @@ -1106,7 +1106,7 @@ fn is_contributor_via_precompile() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(false); + .execute_returns(false); // Assert precompile reports Charlie is a nominator Precompiles::new() @@ -1119,7 +1119,7 @@ fn is_contributor_via_precompile() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); }) } @@ -1191,12 +1191,7 @@ fn reward_info_via_precompile() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(expected_total) - .write(expected_claimed) - .build(), - ); + .execute_returns((expected_total, expected_claimed)); }) } @@ -1738,7 +1733,7 @@ fn asset_erc20_precompiles_supply_and_balance() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(1000 * MOVR)); + .execute_returns(U256::from(1000 * MOVR)); // Access balanceOf through precompile Precompiles::new() @@ -1751,7 +1746,7 @@ fn asset_erc20_precompiles_supply_and_balance() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(1000 * MOVR)); + .execute_returns(U256::from(1000 * MOVR)); }); } @@ -1788,9 +1783,9 @@ fn asset_erc20_precompiles_transfer() { SELECTOR_LOG_TRANSFER, H160::from(ALICE), H160::from(BOB), - EvmDataWriter::new().write(U256::from(400 * MOVR)).build(), + solidity::encode_event_data(U256::from(400 * MOVR)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Make sure BOB has 400 MOVR Precompiles::new() @@ -1803,7 +1798,7 @@ fn asset_erc20_precompiles_transfer() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(400 * MOVR)); + .execute_returns(U256::from(400 * MOVR)); }); } @@ -1840,9 +1835,9 @@ fn asset_erc20_precompiles_approve() { SELECTOR_LOG_APPROVAL, H160::from(ALICE), H160::from(BOB), - EvmDataWriter::new().write(U256::from(400 * MOVR)).build(), + solidity::encode_event_data(U256::from(400 * MOVR)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Transfer tokens from Alice to Charlie by using BOB as origin Precompiles::new() @@ -1861,9 +1856,9 @@ fn asset_erc20_precompiles_approve() { SELECTOR_LOG_TRANSFER, H160::from(ALICE), H160::from(CHARLIE), - EvmDataWriter::new().write(U256::from(400 * MOVR)).build(), + solidity::encode_event_data(U256::from(400 * MOVR)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Make sure CHARLIE has 400 MOVR Precompiles::new() @@ -1876,7 +1871,7 @@ fn asset_erc20_precompiles_approve() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(400 * MOVR)); + .execute_returns(U256::from(400 * MOVR)); }); } @@ -1913,9 +1908,9 @@ fn asset_erc20_precompiles_mint_burn() { SELECTOR_LOG_TRANSFER, H160::default(), H160::from(BOB), - EvmDataWriter::new().write(U256::from(1000 * MOVR)).build(), + solidity::encode_event_data(U256::from(1_000 * MOVR)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Assert the asset has been minted assert_eq!(LocalAssets::total_supply(0u128), 2_000 * MOVR); @@ -1940,9 +1935,9 @@ fn asset_erc20_precompiles_mint_burn() { SELECTOR_LOG_TRANSFER, H160::from(BOB), H160::default(), - EvmDataWriter::new().write(U256::from(500 * MOVR)).build(), + solidity::encode_event_data(U256::from(500 * MOVR)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Assert the asset has been burnt assert_eq!(LocalAssets::total_supply(0u128), 1_500 * MOVR); @@ -1981,7 +1976,7 @@ fn asset_erc20_precompiles_freeze_thaw_account() { ) .expect_cost(6699) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); // Assert account is frozen assert_eq!( @@ -2000,7 +1995,7 @@ fn asset_erc20_precompiles_freeze_thaw_account() { ) .expect_cost(6713) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); // Assert account is not frozen assert!(LocalAssets::can_withdraw(0u128, &AccountId::from(ALICE), 1) @@ -2035,7 +2030,7 @@ fn asset_erc20_precompiles_freeze_thaw_asset() { ) .expect_cost(5548) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); // Assert account is frozen assert_eq!( @@ -2052,7 +2047,7 @@ fn asset_erc20_precompiles_freeze_thaw_asset() { ) .expect_cost(5550) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); // Assert account is not frozen assert!(LocalAssets::can_withdraw(0u128, &AccountId::from(ALICE), 1) @@ -2089,7 +2084,7 @@ fn asset_erc20_precompiles_freeze_transfer_ownership() { ) .expect_cost(6614) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); // No clear way of testing BOB is new owner, other than doing a priviledged function // e.g., transfer_ownership again @@ -2131,7 +2126,7 @@ fn asset_erc20_precompiles_freeze_set_team() { ) .expect_cost(5577) .expect_no_logs() - .execute_returns_encoded(true); + .execute_returns(true); // Bob should be able to mint, freeze, and thaw assert_ok!(LocalAssets::mint( @@ -2194,7 +2189,7 @@ fn xcm_asset_erc20_precompiles_supply_and_balance() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(1000 * MOVR)); + .execute_returns(U256::from(1000 * MOVR)); // Access balanceOf through precompile Precompiles::new() @@ -2207,7 +2202,7 @@ fn xcm_asset_erc20_precompiles_supply_and_balance() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(1000 * MOVR)); + .execute_returns(U256::from(1000 * MOVR)); }); } @@ -2256,9 +2251,9 @@ fn xcm_asset_erc20_precompiles_transfer() { SELECTOR_LOG_TRANSFER, H160::from(ALICE), H160::from(BOB), - EvmDataWriter::new().write(U256::from(400 * MOVR)).build(), + solidity::encode_event_data(U256::from(400 * MOVR)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Make sure BOB has 400 MOVR Precompiles::new() @@ -2271,7 +2266,7 @@ fn xcm_asset_erc20_precompiles_transfer() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(400 * MOVR)); + .execute_returns(U256::from(400 * MOVR)); }); } @@ -2320,9 +2315,9 @@ fn xcm_asset_erc20_precompiles_approve() { SELECTOR_LOG_APPROVAL, H160::from(ALICE), H160::from(BOB), - EvmDataWriter::new().write(U256::from(400 * MOVR)).build(), + solidity::encode_event_data(U256::from(400 * MOVR)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Transfer tokens from Alice to Charlie by using BOB as origin Precompiles::new() @@ -2341,9 +2336,9 @@ fn xcm_asset_erc20_precompiles_approve() { SELECTOR_LOG_TRANSFER, H160::from(ALICE), H160::from(CHARLIE), - EvmDataWriter::new().write(U256::from(400 * MOVR)).build(), + solidity::encode_event_data(U256::from(400 * MOVR)), )) - .execute_returns_encoded(true); + .execute_returns(true); // Make sure CHARLIE has 400 MOVR Precompiles::new() @@ -2356,7 +2351,7 @@ fn xcm_asset_erc20_precompiles_approve() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns_encoded(U256::from(400 * MOVR)); + .execute_returns(U256::from(400 * MOVR)); }); } @@ -2416,7 +2411,7 @@ fn xtokens_precompiles_transfer() { ) .expect_cost(24000) .expect_no_logs() - .execute_returns(vec![]) + .execute_returns(()) }) } @@ -2468,7 +2463,7 @@ fn xtokens_precompiles_transfer_multiasset() { ) .expect_cost(24000) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); }) } @@ -2636,7 +2631,7 @@ fn transact_through_signed_precompile_works_v2() { ) .expect_cost(19078) .expect_no_logs() - .execute_returns(vec![]); + .execute_returns(()); }); } @@ -2751,11 +2746,7 @@ fn test_xcm_utils_ml_to_account() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(Address(expected_address_parent)) - .build(), - ); + .execute_returns(Address(expected_address_parent)); let parachain_2000_multilocation = MultiLocation::new(1, X1(Parachain(2000))); let expected_address_parachain: H160 = @@ -2775,11 +2766,7 @@ fn test_xcm_utils_ml_to_account() { ) .expect_cost(1000) .expect_no_logs() - .execute_returns( - EvmDataWriter::new() - .write(Address(expected_address_parachain)) - .build(), - ); + .execute_returns(Address(expected_address_parachain)); let alice_in_parachain_2000_multilocation = MultiLocation::new( 1, @@ -2823,7 +2810,7 @@ fn test_xcm_utils_weight_message() { .prepare_test(ALICE, xcm_utils_precompile_address, input) .expect_cost(0) .expect_no_logs() - .execute_returns(EvmDataWriter::new().write(expected_weight).build()); + .execute_returns(expected_weight); }); } @@ -2842,7 +2829,7 @@ fn test_xcm_utils_get_units_per_second() { .prepare_test(ALICE, xcm_utils_precompile_address, input) .expect_cost(1000) .expect_no_logs() - .execute_returns(EvmDataWriter::new().write(expected_units).build()); + .execute_returns(expected_units); }); }