difftreelog
Merge branch 'develop' into tests/generalization
in: master
33 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2321,7 +2321,7 @@
[[package]]
name = "evm-coder"
-version = "0.1.5"
+version = "0.1.6"
dependencies = [
"ethereum 0.14.0",
"evm-coder-procedural",
crates/evm-coder/CHANGELOG.mddiffbeforeafterboth--- a/crates/evm-coder/CHANGELOG.md
+++ b/crates/evm-coder/CHANGELOG.md
@@ -3,6 +3,13 @@
All notable changes to this project will be documented in this file.
<!-- bureaucrate goes here -->
+## [v0.1.6] - 2023-01-12
+
+### Added
+- Support Option<T> type.
+### Removed
+- Frontier dependency.
+
## [v0.1.5] - 2022-11-30
### Added
crates/evm-coder/Cargo.tomldiffbeforeafterboth--- a/crates/evm-coder/Cargo.toml
+++ b/crates/evm-coder/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "evm-coder"
-version = "0.1.5"
+version = "0.1.6"
license = "GPLv3"
edition = "2021"
crates/evm-coder/src/abi/impls.rsdiffbeforeafterboth--- a/crates/evm-coder/src/abi/impls.rs
+++ b/crates/evm-coder/src/abi/impls.rs
@@ -258,3 +258,39 @@
impl_tuples! {A B C D E F G H}
impl_tuples! {A B C D E F G H I}
impl_tuples! {A B C D E F G H I J}
+
+//----- impls for Option -----
+impl<T: AbiType> AbiType for Option<T> {
+ const SIGNATURE: SignatureUnit = <(bool, T)>::SIGNATURE;
+
+ fn is_dynamic() -> bool {
+ <(bool, T)>::is_dynamic()
+ }
+
+ fn size() -> usize {
+ <(bool, T)>::size()
+ }
+}
+
+impl<T: AbiWrite + AbiType + Default> AbiWrite for Option<T> {
+ fn abi_write(&self, writer: &mut AbiWriter) {
+ match self {
+ Some(value) => (true, value).abi_write(writer),
+ None => (false, T::default()).abi_write(writer),
+ }
+ }
+}
+
+impl<T> AbiRead for Option<T>
+where
+ Self: AbiType,
+ T: AbiRead + AbiType,
+{
+ fn abi_read(reader: &mut AbiReader) -> Result<Self>
+ where
+ Self: Sized,
+ {
+ let (status, value) = <(bool, T)>::abi_read(reader)?;
+ Ok(if status { Some(value) } else { None })
+ }
+}
crates/evm-coder/src/abi/test.rsdiffbeforeafterboth--- a/crates/evm-coder/src/abi/test.rs
+++ b/crates/evm-coder/src/abi/test.rs
@@ -538,3 +538,68 @@
assert_eq!(p1, 0x0a);
assert_eq!(p2, 0x0b);
}
+
+#[test]
+fn encode_decode_option_uint8_some() {
+ test_impl::<Option<u8>>(
+ 0xdeadbeef,
+ Some(44),
+ &hex!(
+ "
+ deadbeef
+ 0000000000000000000000000000000000000000000000000000000000000001
+ 000000000000000000000000000000000000000000000000000000000000002c
+ "
+ ),
+ );
+}
+
+#[test]
+fn encode_decode_option_uint8_none() {
+ test_impl::<Option<u8>>(
+ 0xdeadbeef,
+ None,
+ &hex!(
+ "
+ deadbeef
+ 0000000000000000000000000000000000000000000000000000000000000000
+ 0000000000000000000000000000000000000000000000000000000000000000
+ "
+ ),
+ );
+}
+
+#[test]
+fn encode_decode_option_string_some() {
+ test_impl::<Option<String>>(
+ 0xdeadbeef,
+ Some("some string".to_string()),
+ &hex!(
+ "
+ deadbeef
+ 0000000000000000000000000000000000000000000000000000000000000020
+ 0000000000000000000000000000000000000000000000000000000000000001
+ 0000000000000000000000000000000000000000000000000000000000000040
+ 000000000000000000000000000000000000000000000000000000000000000b
+ 736f6d6520737472696e67000000000000000000000000000000000000000000
+ "
+ ),
+ );
+}
+
+#[test]
+fn encode_decode_option_string_none() {
+ test_impl::<Option<String>>(
+ 0xdeadbeef,
+ None,
+ &hex!(
+ "
+ deadbeef
+ 0000000000000000000000000000000000000000000000000000000000000020
+ 0000000000000000000000000000000000000000000000000000000000000000
+ 0000000000000000000000000000000000000000000000000000000000000040
+ 0000000000000000000000000000000000000000000000000000000000000000
+ "
+ ),
+ );
+}
crates/evm-coder/src/solidity/impls.rsdiffbeforeafterboth--- a/crates/evm-coder/src/solidity/impls.rs
+++ b/crates/evm-coder/src/solidity/impls.rs
@@ -121,3 +121,59 @@
impl_tuples! {A B C D E F G H}
impl_tuples! {A B C D E F G H I}
impl_tuples! {A B C D E F G H I J}
+
+//----- impls for Option -----
+impl<T: SolidityTypeName + 'static> SolidityTypeName for Option<T> {
+ fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {
+ write!(writer, "{}", tc.collect_struct::<Self>())
+ }
+ fn is_simple() -> bool {
+ false
+ }
+ fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {
+ write!(writer, "{}(", tc.collect_struct::<Self>())?;
+ bool::solidity_default(writer, tc)?;
+ write!(writer, ", ");
+ T::solidity_default(writer, tc)?;
+ write!(writer, ")")
+ }
+}
+
+impl<T: SolidityTypeName> super::SolidityStructTy for Option<T> {
+ fn generate_solidity_interface(tc: &TypeCollector) -> String {
+ let mut solidity_name = "Option".to_string();
+ let mut generic_name = String::new();
+ T::solidity_name(&mut generic_name, tc);
+ solidity_name.push(
+ generic_name
+ .chars()
+ .next()
+ .expect("Generic name is empty")
+ .to_ascii_uppercase(),
+ );
+ solidity_name.push_str(&generic_name[1..]);
+
+ let interface = super::SolidityStruct {
+ docs: &[" Optional value"],
+ name: solidity_name.as_str(),
+ fields: (
+ super::SolidityStructField::<bool> {
+ docs: &[" Shows the status of accessibility of value"],
+ name: "status",
+ ty: ::core::marker::PhantomData,
+ },
+ super::SolidityStructField::<T> {
+ docs: &[" Actual value if `status` is true"],
+ name: "value",
+ ty: ::core::marker::PhantomData,
+ },
+ ),
+ };
+
+ let mut out = String::new();
+ let _ = interface.format(&mut out, tc);
+ tc.collect(out);
+
+ solidity_name.to_string()
+ }
+}
crates/evm-coder/src/solidity/mod.rsdiffbeforeafterboth--- a/crates/evm-coder/src/solidity/mod.rs
+++ b/crates/evm-coder/src/solidity/mod.rs
@@ -456,13 +456,13 @@
Ok(())
}
}
-pub struct SolidityStruct<F> {
- pub docs: &'static [&'static str],
+pub struct SolidityStruct<'a, F> {
+ pub docs: &'a [&'a str],
// pub generics:
- pub name: &'static str,
+ pub name: &'a str,
pub fields: F,
}
-impl<F> SolidityStruct<F>
+impl<F> SolidityStruct<'_, F>
where
F: SolidityItems,
{
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -284,6 +284,11 @@
fn collection_limits(&self) -> Result<Vec<eth::CollectionLimit>> {
let limits = &self.collection.limits;
+ let convert_value_from_bool = |ob: Option<bool>| match ob {
+ Some(b) => Some(b as u32),
+ None => None,
+ };
+
Ok(vec![
eth::CollectionLimit::new(
eth::CollectionLimitField::AccountTokenOwnership,
@@ -297,15 +302,15 @@
.sponsored_data_rate_limit
.and_then(|limit| {
if let SponsoringRateLimit::Blocks(blocks) = limit {
- Some(eth::CollectionLimit::new::<u32>(
+ Some(eth::CollectionLimit::new(
eth::CollectionLimitField::SponsoredDataRateLimit,
- blocks,
+ Some(blocks),
))
} else {
None
}
})
- .unwrap_or(eth::CollectionLimit::new::<u32>(
+ .unwrap_or(eth::CollectionLimit::new(
eth::CollectionLimitField::SponsoredDataRateLimit,
Default::default(),
)),
@@ -320,15 +325,15 @@
),
eth::CollectionLimit::new(
eth::CollectionLimitField::OwnerCanTransfer,
- limits.owner_can_transfer,
+ convert_value_from_bool(limits.owner_can_transfer),
),
eth::CollectionLimit::new(
eth::CollectionLimitField::OwnerCanDestroy,
- limits.owner_can_destroy,
+ convert_value_from_bool(limits.owner_can_destroy),
),
eth::CollectionLimit::new(
eth::CollectionLimitField::TransferEnabled,
- limits.transfers_enabled,
+ convert_value_from_bool(limits.transfers_enabled),
),
])
}
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -66,71 +66,6 @@
T::CrossAccountId::from_sub(account_id)
}
-/// Ethereum representation of Optional value with uint256.
-#[derive(Debug, Default, AbiCoder)]
-pub struct OptionUint {
- status: bool,
- value: uint256,
-}
-
-impl From<u32> for OptionUint {
- fn from(value: u32) -> Self {
- Self {
- status: true,
- value: uint256::from(value),
- }
- }
-}
-
-impl From<Option<u32>> for OptionUint {
- fn from(value: Option<u32>) -> Self {
- match value {
- Some(value) => Self {
- status: true,
- value: value.into(),
- },
- None => Self {
- status: false,
- value: Default::default(),
- },
- }
- }
-}
-
-impl From<bool> for OptionUint {
- fn from(value: bool) -> Self {
- Self {
- status: true,
- value: if value {
- uint256::from(1)
- } else {
- Default::default()
- },
- }
- }
-}
-
-impl From<Option<bool>> for OptionUint {
- fn from(value: Option<bool>) -> Self {
- match value {
- Some(value) => Self::from(value),
- None => Self {
- status: false,
- value: Default::default(),
- },
- }
- }
-}
-
-/// Ethereum representation of Optional value with CrossAddress.
-#[derive(Debug, Default, AbiCoder)]
-pub struct OptionCrossAddress {
- /// Whether or not this CrossAdress is valid and has meaning.
- pub status: bool,
- /// The underlying CrossAddress value. If the status is false, can be set to whatever.
- pub value: CrossAddress,
-}
-
/// Cross account struct
#[derive(Debug, Default, AbiCoder)]
pub struct CrossAddress {
@@ -252,23 +187,23 @@
#[derive(Debug, Default, AbiCoder)]
pub struct CollectionLimit {
field: CollectionLimitField,
- value: OptionUint,
+ value: Option<uint256>,
}
impl CollectionLimit {
/// Create [`CollectionLimit`] from field and value.
- pub fn new<T>(field: CollectionLimitField, value: T) -> Self
- where
- OptionUint: From<T>,
- {
+ pub fn new(field: CollectionLimitField, value: Option<u32>) -> Self {
Self {
field,
- value: value.into(),
+ value: match value {
+ Some(value) => Some(value.into()),
+ None => None,
+ },
}
}
/// Whether the field contains a value.
pub fn has_value(&self) -> bool {
- self.value.status
+ self.value.is_some()
}
}
@@ -276,52 +211,60 @@
type Error = evm_coder::execution::Error;
fn try_into(self) -> Result<up_data_structs::CollectionLimits, Self::Error> {
- let value = self.value.value.try_into().map_err(|error| {
+ let value = self
+ .value
+ .ok_or::<Self::Error>("can't convert `None` value to boolean".into())?;
+ let value = Some(value.try_into().map_err(|error| {
Self::Error::Revert(format!(
"can't convert value to u32 \"{}\" because: \"{error}\"",
- self.value.value
+ value
))
- })?;
+ })?);
let convert_value_to_bool = || match value {
- 0 => Ok(false),
- 1 => Ok(true),
- _ => {
- return Err(Self::Error::Revert(format!(
- "can't convert value to boolean \"{value}\""
- )))
- }
+ Some(value) => match value {
+ 0 => Ok(Some(false)),
+ 1 => Ok(Some(true)),
+ _ => {
+ return Err(Self::Error::Revert(format!(
+ "can't convert value to boolean \"{value}\""
+ )))
+ }
+ },
+ None => Ok(None),
};
let mut limits = up_data_structs::CollectionLimits::default();
match self.field {
CollectionLimitField::AccountTokenOwnership => {
- limits.account_token_ownership_limit = Some(value);
+ limits.account_token_ownership_limit = value;
}
CollectionLimitField::SponsoredDataSize => {
- limits.sponsored_data_size = Some(value);
+ limits.sponsored_data_size = value;
}
CollectionLimitField::SponsoredDataRateLimit => {
- limits.sponsored_data_rate_limit =
- Some(up_data_structs::SponsoringRateLimit::Blocks(value));
+ limits.sponsored_data_rate_limit = match value {
+ Some(value) => Some(up_data_structs::SponsoringRateLimit::Blocks(value)),
+ None => None,
+ };
}
CollectionLimitField::TokenLimit => {
- limits.token_limit = Some(value);
+ limits.token_limit = value;
}
CollectionLimitField::SponsorTransferTimeout => {
- limits.sponsor_transfer_timeout = Some(value);
+ limits.sponsor_transfer_timeout = value;
}
CollectionLimitField::SponsorApproveTimeout => {
- limits.sponsor_approve_timeout = Some(value);
+ limits.sponsor_approve_timeout = value;
}
CollectionLimitField::OwnerCanTransfer => {
- limits.owner_can_transfer = Some(convert_value_to_bool()?);
+ limits.owner_can_transfer = convert_value_to_bool()?;
}
CollectionLimitField::OwnerCanDestroy => {
- limits.owner_can_destroy = Some(convert_value_to_bool()?);
+ limits.owner_can_destroy = convert_value_to_bool()?;
}
CollectionLimitField::TransferEnabled => {
- limits.transfers_enabled = Some(convert_value_to_bool()?);
+ limits.transfers_enabled = convert_value_to_bool()?;
}
};
Ok(limits)
pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -175,16 +175,10 @@
///
/// @param contractAddress The contract for which a sponsor is requested.
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
- fn sponsor(&self, contract_address: address) -> Result<eth::OptionCrossAddress> {
+ fn sponsor(&self, contract_address: address) -> Result<Option<eth::CrossAddress>> {
Ok(match Pallet::<T>::get_sponsor(contract_address) {
- Some(ref value) => eth::OptionCrossAddress {
- status: true,
- value: eth::CrossAddress::from_sub_cross_account::<T>(value),
- },
- None => eth::OptionCrossAddress {
- status: false,
- value: Default::default(),
- },
+ Some(ref value) => Some(eth::CrossAddress::from_sub_cross_account::<T>(value)),
+ None => None,
})
}
pallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/evm-contract-helpers/src/stubs/ContractHelpers.soldiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
+++ b/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
@@ -281,10 +281,10 @@
uint256 sub;
}
-/// Ethereum representation of Optional value with CrossAddress.
+/// Optional value
struct OptionCrossAddress {
- /// Whether or not this CrossAdress is valid and has meaning.
+ /// Shows the status of accessibility of value
bool status;
- /// The underlying CrossAddress value. If the status is false, can be set to whatever.
+ /// Actual value if `status` is true
CrossAddress value;
}
pallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth--- a/pallets/fungible/src/stubs/UniqueFungible.sol
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -466,12 +466,14 @@
/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
struct CollectionLimit {
CollectionLimitField field;
- OptionUint value;
+ OptionUint256 value;
}
-/// Ethereum representation of Optional value with uint256.
-struct OptionUint {
+/// Optional value
+struct OptionUint256 {
+ /// Shows the status of accessibility of value
bool status;
+ /// Actual value if `status` is true
uint256 value;
}
pallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterbothbinary blob — no preview
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -608,12 +608,14 @@
/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
struct CollectionLimit {
CollectionLimitField field;
- OptionUint value;
+ OptionUint256 value;
}
-/// Ethereum representation of Optional value with uint256.
-struct OptionUint {
+/// Optional value
+struct OptionUint256 {
+ /// Shows the status of accessibility of value
bool status;
+ /// Actual value if `status` is true
uint256 value;
}
pallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -608,12 +608,14 @@
/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
struct CollectionLimit {
CollectionLimitField field;
- OptionUint value;
+ OptionUint256 value;
}
-/// Ethereum representation of Optional value with uint256.
-struct OptionUint {
+/// Optional value
+struct OptionUint256 {
+ /// Shows the status of accessibility of value
bool status;
+ /// Actual value if `status` is true
uint256 value;
}
runtime/common/identity.rsdiffbeforeafterboth--- a/runtime/common/identity.rs
+++ b/runtime/common/identity.rs
@@ -24,9 +24,6 @@
transaction_validity::{TransactionValidity, ValidTransaction, TransactionValidityError},
};
-#[cfg(feature = "collator-selection")]
-use sp_runtime::transaction_validity::InvalidTransaction;
-
#[derive(Debug, Encode, Decode, PartialEq, Eq, Clone, TypeInfo)]
pub struct DisableIdentityCalls;
tests/src/eth/abi/fungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/fungible.json
+++ b/tests/src/eth/abi/fungible.json
@@ -222,7 +222,7 @@
{ "internalType": "bool", "name": "status", "type": "bool" },
{ "internalType": "uint256", "name": "value", "type": "uint256" }
],
- "internalType": "struct OptionUint",
+ "internalType": "struct OptionUint256",
"name": "value",
"type": "tuple"
}
@@ -508,7 +508,7 @@
{ "internalType": "bool", "name": "status", "type": "bool" },
{ "internalType": "uint256", "name": "value", "type": "uint256" }
],
- "internalType": "struct OptionUint",
+ "internalType": "struct OptionUint256",
"name": "value",
"type": "tuple"
}
tests/src/eth/abi/fungibleDeprecated.jsondiffbeforeafterboth--- a/tests/src/eth/abi/fungibleDeprecated.json
+++ b/tests/src/eth/abi/fungibleDeprecated.json
@@ -88,14 +88,5 @@
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
- },
- {
- "inputs": [
- { "internalType": "address", "name": "newOwner", "type": "address" }
- ],
- "name": "changeCollectionOwner",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
}
]
tests/src/eth/abi/nonFungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/nonFungible.json
+++ b/tests/src/eth/abi/nonFungible.json
@@ -51,12 +51,6 @@
},
{
"anonymous": false,
- "inputs": [],
- "name": "MintingFinished",
- "type": "event"
- },
- {
- "anonymous": false,
"inputs": [
{
"indexed": true,
@@ -252,7 +246,7 @@
{ "internalType": "bool", "name": "status", "type": "bool" },
{ "internalType": "uint256", "name": "value", "type": "uint256" }
],
- "internalType": "struct OptionUint",
+ "internalType": "struct OptionUint256",
"name": "value",
"type": "tuple"
}
@@ -420,13 +414,6 @@
"name": "description",
"outputs": [{ "internalType": "string", "name": "", "type": "string" }],
"stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [],
- "name": "finishMinting",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
- "stateMutability": "nonpayable",
"type": "function"
},
{
@@ -513,13 +500,6 @@
"name": "mintWithTokenURI",
"outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
"stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [],
- "name": "mintingFinished",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
- "stateMutability": "view",
"type": "function"
},
{
@@ -670,7 +650,7 @@
{ "internalType": "bool", "name": "status", "type": "bool" },
{ "internalType": "uint256", "name": "value", "type": "uint256" }
],
- "internalType": "struct OptionUint",
+ "internalType": "struct OptionUint256",
"name": "value",
"type": "tuple"
}
tests/src/eth/abi/reFungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/reFungible.json
+++ b/tests/src/eth/abi/reFungible.json
@@ -51,12 +51,6 @@
},
{
"anonymous": false,
- "inputs": [],
- "name": "MintingFinished",
- "type": "event"
- },
- {
- "anonymous": false,
"inputs": [
{
"indexed": true,
@@ -234,7 +228,7 @@
{ "internalType": "bool", "name": "status", "type": "bool" },
{ "internalType": "uint256", "name": "value", "type": "uint256" }
],
- "internalType": "struct OptionUint",
+ "internalType": "struct OptionUint256",
"name": "value",
"type": "tuple"
}
@@ -402,13 +396,6 @@
"name": "description",
"outputs": [{ "internalType": "string", "name": "", "type": "string" }],
"stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [],
- "name": "finishMinting",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
- "stateMutability": "nonpayable",
"type": "function"
},
{
@@ -495,13 +482,6 @@
"name": "mintWithTokenURI",
"outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
"stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [],
- "name": "mintingFinished",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
- "stateMutability": "view",
"type": "function"
},
{
@@ -652,7 +632,7 @@
{ "internalType": "bool", "name": "status", "type": "bool" },
{ "internalType": "uint256", "name": "value", "type": "uint256" }
],
- "internalType": "struct OptionUint",
+ "internalType": "struct OptionUint256",
"name": "value",
"type": "tuple"
}
tests/src/eth/abi/reFungibleDeprecated.jsondiffbeforeafterboth--- a/tests/src/eth/abi/reFungibleDeprecated.json
+++ b/tests/src/eth/abi/reFungibleDeprecated.json
@@ -82,6 +82,17 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
+ { "internalType": "string", "name": "key", "type": "string" },
+ { "internalType": "bytes", "name": "value", "type": "bytes" }
+ ],
+ "name": "setProperty",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "newOwner", "type": "address" }
],
"name": "changeCollectionOwner",
tests/src/eth/abi/reFungibleToken.jsondiffbeforeafterboth--- a/tests/src/eth/abi/reFungibleToken.json
+++ b/tests/src/eth/abi/reFungibleToken.json
@@ -98,16 +98,6 @@
},
{
"inputs": [
- { "internalType": "address", "name": "from", "type": "address" },
- { "internalType": "uint256", "name": "amount", "type": "uint256" }
- ],
- "name": "burnFrom",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
{
"components": [
{ "internalType": "address", "name": "eth", "type": "address" },
tests/src/eth/abi/reFungibleTokenDeprecated.jsondiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/abi/reFungibleTokenDeprecated.json
@@ -0,0 +1,12 @@
+[
+ {
+ "inputs": [
+ { "internalType": "address", "name": "from", "type": "address" },
+ { "internalType": "uint256", "name": "amount", "type": "uint256" }
+ ],
+ "name": "burnFrom",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ }
+]
tests/src/eth/api/ContractHelpers.soldiffbeforeafterboth--- a/tests/src/eth/api/ContractHelpers.sol
+++ b/tests/src/eth/api/ContractHelpers.sol
@@ -181,11 +181,11 @@
Generous
}
-/// Ethereum representation of Optional value with CrossAddress.
+/// Optional value
struct OptionCrossAddress {
- /// Whether or not this CrossAdress is valid and has meaning.
+ /// Shows the status of accessibility of value
bool status;
- /// The underlying CrossAddress value. If the status is false, can be set to whatever.
+ /// Actual value if `status` is true
CrossAddress value;
}
tests/src/eth/api/UniqueFungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -308,12 +308,14 @@
/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
struct CollectionLimit {
CollectionLimitField field;
- OptionUint value;
+ OptionUint256 value;
}
-/// Ethereum representation of Optional value with uint256.
-struct OptionUint {
+/// Optional value
+struct OptionUint256 {
+ /// Shows the status of accessibility of value
bool status;
+ /// Actual value if `status` is true
uint256 value;
}
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -408,12 +408,14 @@
/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
struct CollectionLimit {
CollectionLimitField field;
- OptionUint value;
+ OptionUint256 value;
}
-/// Ethereum representation of Optional value with uint256.
-struct OptionUint {
+/// Optional value
+struct OptionUint256 {
+ /// Shows the status of accessibility of value
bool status;
+ /// Actual value if `status` is true
uint256 value;
}
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -408,12 +408,14 @@
/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
struct CollectionLimit {
CollectionLimitField field;
- OptionUint value;
+ OptionUint256 value;
}
-/// Ethereum representation of Optional value with uint256.
-struct OptionUint {
+/// Optional value
+struct OptionUint256 {
+ /// Shows the status of accessibility of value
bool status;
+ /// Actual value if `status` is true
uint256 value;
}
tests/src/eth/reFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -213,7 +213,7 @@
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = await helper.ethNativeContract.collection(address, 'rft');
- const rftToken = await helper.ethNativeContract.rftTokenById(token.collectionId, token.tokenId, owner);
+ const rftToken = await helper.ethNativeContract.rftTokenById(token.collectionId, token.tokenId, owner, true);
{
await rftToken.methods.approve(operator, 15n).send({from: owner});
tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import {Pallets, requirePalletsOrSkip} from '../util';18import {EthUniqueHelper, expect, itEth, usingEthPlaygrounds} from './util';19import {IKeyringPair} from '@polkadot/types/types';20import {Contract} from 'web3-eth-contract';2122// FIXME: Need erc721 for ReFubgible.23describe('Check ERC721 token URI for ReFungible', () => {24 let donor: IKeyringPair;2526 before(async function() {27 await usingEthPlaygrounds(async (helper, privateKey) => {28 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);2930 donor = await privateKey({filename: __filename});31 });32 });3334 async function setup(helper: EthUniqueHelper, baseUri: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {35 const owner = await helper.eth.createAccountWithBalance(donor);36 const receiver = helper.eth.createAccount();3738 const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Mint collection', 'a', 'b', baseUri);39 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);4041 const result = await contract.methods.mint(receiver).send();4243 const event = result.events.Transfer;44 const tokenId = event.returnValues.tokenId;45 expect(tokenId).to.be.equal('1');46 expect(event.address).to.be.equal(collectionAddress);47 expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');48 expect(event.returnValues.to).to.be.equal(receiver);4950 if (propertyKey && propertyValue) {51 // Set URL or suffix5253 await contract.methods.setProperties(tokenId, [{key: propertyKey, value: Buffer.from(propertyValue)}]).send();54 }5556 return {contract, nextTokenId: tokenId};57 }5859 itEth('Empty tokenURI', async ({helper}) => {60 const {contract, nextTokenId} = await setup(helper, '');61 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('');62 });6364 itEth('TokenURI from url', async ({helper}) => {65 const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URI', 'Token URI');66 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');67 });6869 itEth('TokenURI from baseURI', async ({helper}) => {70 const {contract, nextTokenId} = await setup(helper, 'BaseURI_');71 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_');72 });7374 itEth('TokenURI from baseURI + suffix', async ({helper}) => {75 const suffix = '/some/suffix';76 const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URISuffix', suffix);77 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);78 });79});8081describe('Refungible: Plain calls', () => {82 let donor: IKeyringPair;83 let alice: IKeyringPair;8485 before(async function() {86 await usingEthPlaygrounds(async (helper, privateKey) => {87 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);8889 donor = await privateKey({filename: __filename});90 [alice] = await helper.arrange.createAccounts([50n], donor);91 });92 });9394 itEth('Can perform approve()', async ({helper}) => {95 const owner = await helper.eth.createAccountWithBalance(donor);96 const spender = helper.eth.createAccount();97 const collection = await helper.rft.mintCollection(alice);98 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});99100 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);101 const contract = await helper.ethNativeContract.rftToken(tokenAddress, owner);102103 {104 const result = await contract.methods.approve(spender, 100).send({from: owner});105 const event = result.events.Approval;106 expect(event.address).to.be.equal(tokenAddress);107 expect(event.returnValues.owner).to.be.equal(owner);108 expect(event.returnValues.spender).to.be.equal(spender);109 expect(event.returnValues.value).to.be.equal('100');110 }111112 {113 const allowance = await contract.methods.allowance(owner, spender).call();114 expect(+allowance).to.equal(100);115 }116 });117118 itEth('Can perform approveCross()', async ({helper}) => {119 const owner = await helper.eth.createAccountWithBalance(donor);120 const spender = helper.eth.createAccount();121 const spenderSub = (await helper.arrange.createAccounts([1n], donor))[0];122 const spenderCrossEth = helper.ethCrossAccount.fromAddress(spender);123 const spenderCrossSub = helper.ethCrossAccount.fromKeyringPair(spenderSub);124125126 const collection = await helper.rft.mintCollection(alice);127 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});128129 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);130 const contract = await helper.ethNativeContract.rftToken(tokenAddress, owner);131132 {133 const result = await contract.methods.approveCross(spenderCrossEth, 100).send({from: owner});134 const event = result.events.Approval;135 expect(event.address).to.be.equal(tokenAddress);136 expect(event.returnValues.owner).to.be.equal(owner);137 expect(event.returnValues.spender).to.be.equal(spender);138 expect(event.returnValues.value).to.be.equal('100');139 }140141 {142 const allowance = await contract.methods.allowance(owner, spender).call();143 expect(+allowance).to.equal(100);144 }145146147 {148 const result = await contract.methods.approveCross(spenderCrossSub, 100).send({from: owner});149 const event = result.events.Approval;150 expect(event.address).to.be.equal(tokenAddress);151 expect(event.returnValues.owner).to.be.equal(owner);152 expect(event.returnValues.spender).to.be.equal(helper.address.substrateToEth(spenderSub.address));153 expect(event.returnValues.value).to.be.equal('100');154 }155156 {157 const allowance = await collection.getTokenApprovedPieces(tokenId, {Ethereum: owner}, {Substrate: spenderSub.address});158 expect(allowance).to.equal(100n);159 }160161 {162 //TO-DO expect with future allowanceCross(owner, spenderCrossEth).call()163 }164 });165166 itEth('Non-owner and non admin cannot approveCross', async ({helper}) => {167 const nonOwner = await helper.eth.createAccountWithBalance(donor);168 const nonOwnerCross = helper.ethCrossAccount.fromAddress(nonOwner);169 const owner = await helper.eth.createAccountWithBalance(donor);170 const collection = await helper.rft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});171 const token = await collection.mintToken(alice, 100n, {Ethereum: owner});172173 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, token.tokenId);174 const tokenEvm = await helper.ethNativeContract.rftToken(tokenAddress, owner);175176 await expect(tokenEvm.methods.approveCross(nonOwnerCross, 20).call({from: nonOwner})).to.be.rejectedWith('CantApproveMoreThanOwned');177 });178179 [180 'transferFrom',181 'transferFromCross',182 ].map(testCase =>183 itEth(`Can perform ${testCase}`, async ({helper}) => {184 const isCross = testCase === 'transferFromCross';185 const owner = await helper.eth.createAccountWithBalance(donor);186 const ownerCross = helper.ethCrossAccount.fromAddress(owner);187 const spender = await helper.eth.createAccountWithBalance(donor);188 const receiverEth = helper.eth.createAccount();189 const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiverEth);190 const [receiverSub] = await helper.arrange.createAccounts([1n], donor);191 const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(receiverSub);192193 const collection = await helper.rft.mintCollection(alice);194 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});195196 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);197 const contract = await helper.ethNativeContract.rftToken(tokenAddress, owner);198199 await contract.methods.approve(spender, 100).send({from: owner});200201 // 1. Can transfer from202 // 1.1 Plain ethereum or cross address:203 {204 const result = await contract.methods[testCase](205 isCross ? ownerCross : owner,206 isCross ? receiverCrossEth : receiverEth,207 49,208 ).send({from: spender});209210 // Check events:211 const transferEvent = result.events.Transfer;212 expect(transferEvent.address).to.be.equal(tokenAddress);213 expect(transferEvent.returnValues.from).to.be.equal(owner);214 expect(transferEvent.returnValues.to).to.be.equal(receiverEth);215 expect(transferEvent.returnValues.value).to.be.equal('49');216217 const approvalEvent = result.events.Approval;218 expect(approvalEvent.address).to.be.equal(tokenAddress);219 expect(approvalEvent.returnValues.owner).to.be.equal(owner);220 expect(approvalEvent.returnValues.spender).to.be.equal(spender);221 expect(approvalEvent.returnValues.value).to.be.equal('51');222223 // Check balances:224 const receiverBalance = await contract.methods.balanceOf(receiverEth).call();225 const ownerBalance = await contract.methods.balanceOf(owner).call();226227 expect(+receiverBalance).to.equal(49);228 expect(+ownerBalance).to.equal(151);229 }230231 // 1.2 Cross substrate address:232 if (testCase === 'transferFromCross') {233 const result = await contract.methods.transferFromCross(ownerCross, receiverCrossSub, 51).send({from: spender});234 // Check events:235 const transferEvent = result.events.Transfer;236 expect(transferEvent.address).to.be.equal(tokenAddress);237 expect(transferEvent.returnValues.from).to.be.equal(owner);238 expect(transferEvent.returnValues.to).to.be.equal(helper.address.substrateToEth(receiverSub.address));239 expect(transferEvent.returnValues.value).to.be.equal('51');240241 const approvalEvent = result.events.Approval;242 expect(approvalEvent.address).to.be.equal(tokenAddress);243 expect(approvalEvent.returnValues.owner).to.be.equal(owner);244 expect(approvalEvent.returnValues.spender).to.be.equal(spender);245 expect(approvalEvent.returnValues.value).to.be.equal('0');246247 // Check balances:248 const receiverBalance = await collection.getTokenBalance(tokenId, {Substrate: receiverSub.address});249 const ownerBalance = await contract.methods.balanceOf(owner).call();250 expect(receiverBalance).to.equal(51n);251 expect(+ownerBalance).to.equal(100);252 }253 }));254255 [256 'transfer',257 'transferCross',258 ].map(testCase =>259 itEth(`Can perform ${testCase}()`, async ({helper}) => {260 const isCross = testCase === 'transferCross';261 const owner = await helper.eth.createAccountWithBalance(donor);262 const receiverEth = helper.eth.createAccount();263 const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiverEth);264 const [receiverSub] = await helper.arrange.createAccounts([1n], donor);265 const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(receiverSub);266 const collection = await helper.rft.mintCollection(alice);267 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});268269 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);270 const contract = await helper.ethNativeContract.rftToken(tokenAddress, owner);271272 // 1. Can transfer to plain ethereum or cross-ethereum account:273 {274 const result = await contract.methods[testCase](isCross ? receiverCrossEth : receiverEth, 50).send({from: owner});275 // Check events276 const transferEvent = result.events.Transfer;277 expect(transferEvent.address).to.be.equal(tokenAddress);278 expect(transferEvent.returnValues.from).to.be.equal(owner);279 expect(transferEvent.returnValues.to).to.be.equal(receiverEth);280 expect(transferEvent.returnValues.value).to.be.equal('50');281 // Check balances:282 const ownerBalance = await contract.methods.balanceOf(owner).call();283 const receiverBalance = await contract.methods.balanceOf(receiverEth).call();284 expect(+ownerBalance).to.equal(150);285 expect(+receiverBalance).to.equal(50);286 }287288 // 2. Can transfer to cross-substrate account:289 if(isCross) {290 const result = await contract.methods.transferCross(receiverCrossSub, 50).send({from: owner});291 // Check events:292 const event = result.events.Transfer;293 expect(event.address).to.be.equal(tokenAddress);294 expect(event.returnValues.from).to.be.equal(owner);295 expect(event.returnValues.to).to.be.equal(helper.address.substrateToEth(receiverSub.address));296 expect(event.returnValues.value).to.be.equal('50');297 // Check balances:298 const ownerBalance = await contract.methods.balanceOf(owner).call();299 const receiverBalance = await collection.getTokenBalance(tokenId, {Substrate: receiverSub.address});300 expect(+ownerBalance).to.equal(100);301 expect(receiverBalance).to.equal(50n);302 }303 }));304305 [306 'transfer',307 'transferCross',308 ].map(testCase =>309 itEth(`Cannot ${testCase}() non-owned token`, async ({helper}) => {310 const isCross = testCase === 'transferCross';311 const owner = await helper.eth.createAccountWithBalance(donor);312 const ownerCross = helper.ethCrossAccount.fromAddress(owner);313 const receiverEth = await helper.eth.createAccountWithBalance(donor);314 const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiverEth);315 const collection = await helper.rft.mintCollection(alice);316 const rftOwner = await collection.mintToken(alice, 10n, {Ethereum: owner});317 const rftReceiver = await collection.mintToken(alice, 10n, {Ethereum: receiverEth});318 const tokenIdNonExist = 9999999;319320 const tokenAddress1 = helper.ethAddress.fromTokenId(collection.collectionId, rftOwner.tokenId);321 const tokenAddress2 = helper.ethAddress.fromTokenId(collection.collectionId, rftReceiver.tokenId);322 const tokenAddressNonExist = helper.ethAddress.fromTokenId(collection.collectionId, tokenIdNonExist);323 const tokenEvmOwner = await helper.ethNativeContract.rftToken(tokenAddress1, owner);324 const tokenEvmReceiver = await helper.ethNativeContract.rftToken(tokenAddress2, owner);325 const tokenEvmNonExist = await helper.ethNativeContract.rftToken(tokenAddressNonExist, owner);326327 // 1. Can transfer zero amount (EIP-20):328 await tokenEvmOwner.methods[testCase](isCross ? receiverCrossEth : receiverEth, 0).send({from: owner});329 // 2. Cannot transfer non-owned token:330 await expect(tokenEvmReceiver.methods[testCase](isCross ? ownerCross : owner, 0).send({from: owner})).to.be.rejected;331 await expect(tokenEvmReceiver.methods[testCase](isCross ? ownerCross : owner, 5).send({from: owner})).to.be.rejected;332 // 3. Cannot transfer non-existing token:333 await expect(tokenEvmNonExist.methods[testCase](isCross ? ownerCross : owner, 0).send({from: owner})).to.be.rejected;334 await expect(tokenEvmNonExist.methods[testCase](isCross ? ownerCross : owner, 5).send({from: owner})).to.be.rejected;335336 // 4. Storage is not corrupted:337 expect(await rftOwner.getTop10Owners()).to.deep.eq([{Ethereum: owner.toLowerCase()}]);338 expect(await rftReceiver.getTop10Owners()).to.deep.eq([{Ethereum: receiverEth.toLowerCase()}]);339 expect(await helper.rft.getTokenTop10Owners(collection.collectionId, tokenIdNonExist)).to.deep.eq([]);340341 // 4.1 Tokens can be transferred:342 await tokenEvmOwner.methods[testCase](isCross ? receiverCrossEth : receiverEth, 10).send({from: owner});343 await tokenEvmReceiver.methods[testCase](isCross ? ownerCross : owner, 10).send({from: receiverEth});344 expect(await rftOwner.getTop10Owners()).to.deep.eq([{Ethereum: receiverEth.toLowerCase()}]);345 expect(await rftReceiver.getTop10Owners()).to.deep.eq([{Ethereum: owner.toLowerCase()}]);346 }));347348 itEth('Can perform repartition()', async ({helper}) => {349 const owner = await helper.eth.createAccountWithBalance(donor);350 const receiver = await helper.eth.createAccountWithBalance(donor);351 const collection = await helper.rft.mintCollection(alice);352 const {tokenId} = await collection.mintToken(alice, 100n, {Ethereum: owner});353354 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);355 const contract = await helper.ethNativeContract.rftToken(tokenAddress, owner);356357 await contract.methods.repartition(200).send({from: owner});358 expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(200);359 await contract.methods.transfer(receiver, 110).send({from: owner});360 expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(90);361 expect(+await contract.methods.balanceOf(receiver).call()).to.be.equal(110);362363 await expect(contract.methods.repartition(80).send({from: owner})).to.eventually.be.rejected; // Transaction is reverted364365 await contract.methods.transfer(receiver, 90).send({from: owner});366 expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(0);367 expect(+await contract.methods.balanceOf(receiver).call()).to.be.equal(200);368369 await contract.methods.repartition(150).send({from: receiver});370 await expect(contract.methods.transfer(owner, 160).send({from: receiver})).to.eventually.be.rejected; // Transaction is reverted371 expect(+await contract.methods.balanceOf(receiver).call()).to.be.equal(150);372 });373374 itEth('Can repartition with increased amount', async ({helper}) => {375 const owner = await helper.eth.createAccountWithBalance(donor);376 const collection = await helper.rft.mintCollection(alice);377 const {tokenId} = await collection.mintToken(alice, 100n, {Ethereum: owner});378379 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);380 const contract = await helper.ethNativeContract.rftToken(tokenAddress, owner);381382 const result = await contract.methods.repartition(200).send();383384 const event = result.events.Transfer;385 expect(event.address).to.be.equal(tokenAddress);386 expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');387 expect(event.returnValues.to).to.be.equal(owner);388 expect(event.returnValues.value).to.be.equal('100');389 });390391 itEth('Can repartition with decreased amount', async ({helper}) => {392 const owner = await helper.eth.createAccountWithBalance(donor);393 const collection = await helper.rft.mintCollection(alice);394 const {tokenId} = await collection.mintToken(alice, 100n, {Ethereum: owner});395396 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);397 const contract = await helper.ethNativeContract.rftToken(tokenAddress, owner);398399 const result = await contract.methods.repartition(50).send();400 const event = result.events.Transfer;401 expect(event.address).to.be.equal(tokenAddress);402 expect(event.returnValues.from).to.be.equal(owner);403 expect(event.returnValues.to).to.be.equal('0x0000000000000000000000000000000000000000');404 expect(event.returnValues.value).to.be.equal('50');405 });406407 itEth('Receiving Transfer event on burning into full ownership', async ({helper}) => {408 const caller = await helper.eth.createAccountWithBalance(donor);409 const receiver = await helper.eth.createAccountWithBalance(donor);410 const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Devastation', '6', '6');411 const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);412413 const result = await contract.methods.mint(caller).send();414 const tokenId = result.events.Transfer.returnValues.tokenId;415 const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);416 const tokenContract = await helper.ethNativeContract.rftToken(tokenAddress, caller, true);417418 await tokenContract.methods.repartition(2).send();419 await tokenContract.methods.transfer(receiver, 1).send();420421 const events: any = [];422 contract.events.allEvents((_: any, event: any) => {423 events.push(event);424 });425 await tokenContract.methods.burnFrom(caller, 1).send();426427 if (events.length == 0) await helper.wait.newBlocks(1);428 const event = events[0];429 expect(event.address).to.be.equal(collectionAddress);430 expect(event.returnValues.from).to.be.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');431 expect(event.returnValues.to).to.be.equal(receiver);432 expect(event.returnValues.tokenId).to.be.equal(tokenId);433 });434435 itEth('Can perform burnFromCross()', async ({helper}) => {436 const owner = await helper.eth.createAccountWithBalance(donor);437 const ownerSub = (await helper.arrange.createAccounts([10n], donor))[0];438 const ownerCross = helper.ethCrossAccount.fromAddress(owner);439 const spender = await helper.eth.createAccountWithBalance(donor);440441 const spenderCrossEth = helper.ethCrossAccount.fromAddress(spender);442 const ownerSubCross = helper.ethCrossAccount.fromKeyringPair(ownerSub);443444 const collection = await helper.rft.mintCollection(alice);445 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});446447448 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);449 const contract = await helper.ethNativeContract.rftToken(tokenAddress, owner);450451 {452 await contract.methods.approveCross(spenderCrossEth, 100).send({from: owner});453454 await expect(contract.methods.burnFromCross(ownerCross, 50).send({from: spender})).to.be.fulfilled;455 await expect(contract.methods.burnFromCross(ownerCross, 100).send({from: spender})).to.be.rejected;456 expect(await contract.methods.balanceOf(owner).call({from: owner})).to.be.equal('150');457 }458 {459 const {tokenId} = await collection.mintToken(alice, 200n, {Substrate: ownerSub.address});460 await collection.approveToken(ownerSub, tokenId, {Ethereum: spender}, 100n);461 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);462 const contract = await helper.ethNativeContract.rftToken(tokenAddress, owner);463464 await expect(contract.methods.burnFromCross(ownerSubCross, 50).send({from: spender})).to.be.fulfilled;465 await expect(contract.methods.burnFromCross(ownerSubCross, 100).send({from: spender})).to.be.rejected;466 expect(await collection.getTokenBalance(tokenId, {Substrate: ownerSub.address})).to.be.equal(150n);467 }468 });469});470471describe('Refungible: Fees', () => {472 let donor: IKeyringPair;473 let alice: IKeyringPair;474475 before(async function() {476 await usingEthPlaygrounds(async (helper, privateKey) => {477 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);478479 donor = await privateKey({filename: __filename});480 [alice] = await helper.arrange.createAccounts([50n], donor);481 });482 });483484 itEth('approve() call fee is less than 0.2UNQ', async ({helper}) => {485 const owner = await helper.eth.createAccountWithBalance(donor);486 const spender = helper.eth.createAccount();487 const collection = await helper.rft.mintCollection(alice);488 const {tokenId} = await collection.mintToken(alice, 100n, {Ethereum: owner});489490 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);491 const contract = await helper.ethNativeContract.rftToken(tokenAddress, owner);492493 const cost = await helper.eth.recordCallFee(owner, () => contract.methods.approve(spender, 100).send({from: owner}));494 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));495 });496497 itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {498 const owner = await helper.eth.createAccountWithBalance(donor);499 const spender = await helper.eth.createAccountWithBalance(donor);500 const collection = await helper.rft.mintCollection(alice);501 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});502503 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);504 const contract = await helper.ethNativeContract.rftToken(tokenAddress, owner);505506 await contract.methods.approve(spender, 100).send({from: owner});507508 const cost = await helper.eth.recordCallFee(spender, () => contract.methods.transferFrom(owner, spender, 100).send({from: spender}));509 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));510 });511512 itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {513 const owner = await helper.eth.createAccountWithBalance(donor);514 const receiver = helper.eth.createAccount();515 const collection = await helper.rft.mintCollection(alice);516 const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});517518 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);519 const contract = await helper.ethNativeContract.rftToken(tokenAddress, owner);520521 const cost = await helper.eth.recordCallFee(owner, () => contract.methods.transfer(receiver, 100).send({from: owner}));522 expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));523 });524});525526describe('Refungible: Substrate calls', () => {527 let donor: IKeyringPair;528 let alice: IKeyringPair;529530 before(async function() {531 await usingEthPlaygrounds(async (helper, privateKey) => {532 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);533534 donor = await privateKey({filename: __filename});535 [alice] = await helper.arrange.createAccounts([50n], donor);536 });537 });538539 itEth('Events emitted for approve()', async ({helper}) => {540 const receiver = helper.eth.createAccount();541 const collection = await helper.rft.mintCollection(alice);542 const token = await collection.mintToken(alice, 200n);543544 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, token.tokenId);545 const contract = await helper.ethNativeContract.rftToken(tokenAddress);546547 const events: any = [];548 contract.events.allEvents((_: any, event: any) => {549 events.push(event);550 });551552 expect(await token.approve(alice, {Ethereum: receiver}, 100n)).to.be.true;553 if (events.length == 0) await helper.wait.newBlocks(1);554 const event = events[0];555556 expect(event.event).to.be.equal('Approval');557 expect(event.address).to.be.equal(tokenAddress);558 expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));559 expect(event.returnValues.spender).to.be.equal(receiver);560 expect(event.returnValues.value).to.be.equal('100');561 });562563 itEth('Events emitted for transferFrom()', async ({helper}) => {564 const [bob] = await helper.arrange.createAccounts([10n], donor);565 const receiver = helper.eth.createAccount();566 const collection = await helper.rft.mintCollection(alice);567 const token = await collection.mintToken(alice, 200n);568 await token.approve(alice, {Substrate: bob.address}, 100n);569570 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, token.tokenId);571 const contract = await helper.ethNativeContract.rftToken(tokenAddress);572573 const events: any = [];574 contract.events.allEvents((_: any, event: any) => {575 events.push(event);576 });577578 expect(await token.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver}, 51n)).to.be.true;579 if (events.length == 0) await helper.wait.newBlocks(1);580581 let event = events[0];582 expect(event.event).to.be.equal('Transfer');583 expect(event.address).to.be.equal(tokenAddress);584 expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));585 expect(event.returnValues.to).to.be.equal(receiver);586 expect(event.returnValues.value).to.be.equal('51');587588 event = events[1];589 expect(event.event).to.be.equal('Approval');590 expect(event.address).to.be.equal(tokenAddress);591 expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));592 expect(event.returnValues.spender).to.be.equal(helper.address.substrateToEth(bob.address));593 expect(event.returnValues.value).to.be.equal('49');594 });595596 itEth('Events emitted for transfer()', async ({helper}) => {597 const receiver = helper.eth.createAccount();598 const collection = await helper.rft.mintCollection(alice);599 const token = await collection.mintToken(alice, 200n);600601 const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, token.tokenId);602 const contract = await helper.ethNativeContract.rftToken(tokenAddress);603604 const events: any = [];605 contract.events.allEvents((_: any, event: any) => {606 events.push(event);607 });608609 expect(await token.transfer(alice, {Ethereum: receiver}, 51n)).to.be.true;610 if (events.length == 0) await helper.wait.newBlocks(1);611 const event = events[0];612613 expect(event.event).to.be.equal('Transfer');614 expect(event.address).to.be.equal(tokenAddress);615 expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));616 expect(event.returnValues.to).to.be.equal(receiver);617 expect(event.returnValues.value).to.be.equal('51');618 });619});620621describe('ERC 1633 implementation', () => {622 let donor: IKeyringPair;623624 before(async function() {625 await usingEthPlaygrounds(async (helper, privateKey) => {626 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);627628 donor = await privateKey({filename: __filename});629 });630 });631632 itEth('Default parent token address and id', async ({helper}) => {633 const owner = await helper.eth.createAccountWithBalance(donor);634635 const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(owner, 'Sands', '', 'GRAIN');636 const collectionContract = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);637638 const result = await collectionContract.methods.mint(owner).send();639 const tokenId = result.events.Transfer.returnValues.tokenId;640641 const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);642 const tokenContract = await helper.ethNativeContract.rftToken(tokenAddress, owner);643644 expect(await tokenContract.methods.parentToken().call()).to.be.equal(collectionAddress);645 expect(await tokenContract.methods.parentTokenId().call()).to.be.equal(tokenId);646 });647});tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -29,6 +29,7 @@
import refungibleAbi from '../../abi/reFungible.json';
import refungibleDeprecatedAbi from '../../abi/reFungibleDeprecated.json';
import refungibleTokenAbi from '../../abi/reFungibleToken.json';
+import refungibleTokenDeprecatedAbi from '../../abi/reFungibleTokenDeprecated.json';
import contractHelpersAbi from '../../abi/contractHelpers.json';
import {ICrossAccountId, TEthereumAccount} from '../../../util/playgrounds/types';
import {TCollectionMode} from '../../../util/playgrounds/types';
@@ -187,17 +188,18 @@
return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller, mergeDeprecated);
}
- async rftToken(address: string, caller?: string) {
+ async rftToken(address: string, caller?: string, mergeDeprecated = false) {
const web3 = this.helper.getWeb3();
- return unlimitedMoneyHack(new web3.eth.Contract(refungibleTokenAbi as any, address, {
+ const abi = mergeDeprecated ? [...refungibleTokenAbi, ...refungibleTokenDeprecatedAbi] : refungibleTokenAbi;
+ return unlimitedMoneyHack(new web3.eth.Contract(abi as any, address, {
gas: this.helper.eth.DEFAULT_GAS,
gasPrice: await this.getGasPrice(),
...(caller ? {from: caller} : {}),
}));
}
- rftTokenById(collectionId: number, tokenId: number, caller?: string) {
- return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);
+ rftTokenById(collectionId: number, tokenId: number, caller?: string, mergeDeprecated = false) {
+ return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller, mergeDeprecated);
}
}