difftreelog
feat updates for createERC721MetadataCompatibleCollections
in: master
13 files changed
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -665,6 +665,11 @@
property_key_from_bytes(b"schemaName").expect(EXPECT_CONVERT_ERROR)
}
+ /// Key "schemaVersion".
+ pub fn schema_version() -> up_data_structs::PropertyKey {
+ property_key_from_bytes(b"schemaVersion").expect(EXPECT_CONVERT_ERROR)
+ }
+
/// Key "baseURI".
pub fn base_uri() -> up_data_structs::PropertyKey {
property_key_from_bytes(b"baseURI").expect(EXPECT_CONVERT_ERROR)
@@ -672,12 +677,12 @@
/// Key "url".
pub fn url() -> up_data_structs::PropertyKey {
- property_key_from_bytes(b"url").expect(EXPECT_CONVERT_ERROR)
+ property_key_from_bytes(b"URI").expect(EXPECT_CONVERT_ERROR)
}
/// Key "suffix".
pub fn suffix() -> up_data_structs::PropertyKey {
- property_key_from_bytes(b"suffix").expect(EXPECT_CONVERT_ERROR)
+ property_key_from_bytes(b"URISuffix").expect(EXPECT_CONVERT_ERROR)
}
/// Key "parentNft".
@@ -685,7 +690,7 @@
property_key_from_bytes(b"parentNft").expect(EXPECT_CONVERT_ERROR)
}
- /// Key "parentNft".
+ /// Key "ERC721Metadata".
pub fn erc721_metadata() -> up_data_structs::PropertyKey {
property_key_from_bytes(b"ERC721Metadata").expect(EXPECT_CONVERT_ERROR)
}
@@ -695,6 +700,9 @@
pub mod value {
use super::*;
+ /// Value "Schema version".
+ pub const SCHEMA_VERSION: &[u8] = b"1.0.0";
+
/// Value "ERC721Metadata".
pub const ERC721_METADATA: &[u8] = b"ERC721Metadata";
@@ -709,7 +717,12 @@
property_value_from_bytes(ERC721_METADATA).expect(EXPECT_CONVERT_ERROR)
}
- /// Value for [`ERC721_METADATA`].
+ /// Value for [`SCHEMA_VERSION`].
+ pub fn schema_version() -> up_data_structs::PropertyValue {
+ property_value_from_bytes(SCHEMA_VERSION).expect(EXPECT_CONVERT_ERROR)
+ }
+
+ /// Value for [`ERC721_METADATA_SUPPORTED`].
pub fn erc721_metadata_supported() -> up_data_structs::PropertyValue {
property_value_from_bytes(ERC721_METADATA_SUPPORTED).expect(EXPECT_CONVERT_ERROR)
}
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -116,7 +116,18 @@
.try_push(up_data_structs::PropertyKeyPermission {
key: key::suffix(),
permission: up_data_structs::PropertyPermission {
- mutable: false,
+ mutable: true,
+ collection_admin: true,
+ token_owner: false,
+ },
+ })
+ .map_err(|e| Error::Revert(format!("{:?}", e)))?;
+
+ token_property_permissions
+ .try_push(up_data_structs::PropertyKeyPermission {
+ key: key::url(),
+ permission: up_data_structs::PropertyPermission {
+ mutable: true,
collection_admin: true,
token_owner: false,
},
@@ -129,6 +140,13 @@
value: property_value::erc721(),
})
.map_err(|e| Error::Revert(format!("{:?}", e)))?;
+
+ properties
+ .try_push(up_data_structs::Property {
+ key: key::schema_version(),
+ value: property_value::schema_version(),
+ })
+ .map_err(|e| Error::Revert(format!("{:?}", e)))?;
properties
.try_push(up_data_structs::Property {
@@ -266,7 +284,7 @@
}
#[weight(<SelfWeightOf<T>>::create_collection())]
- #[solidity(rename_selector = "createERC721MetadataNFTCollection")]
+ #[solidity(rename_selector = "createERC721MetadataCompatibleNFTCollection")]
fn create_nonfungible_collection_with_properties(
&mut self,
caller: caller,
@@ -339,7 +357,7 @@
}
#[weight(<SelfWeightOf<T>>::create_collection())]
- #[solidity(rename_selector = "createERC721MetadataRFTCollection")]
+ #[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]
fn create_refungible_collection_with_properties(
&mut self,
caller: caller,
pallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/stubs/CollectionHelpers.soldiffbeforeafterboth--- a/pallets/unique/src/eth/stubs/CollectionHelpers.sol
+++ b/pallets/unique/src/eth/stubs/CollectionHelpers.sol
@@ -23,7 +23,7 @@
}
/// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0xf62c7aa9
+/// @dev the ERC-165 identifier for this interface is 0x95eb98f4
contract CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
/// Create an NFT collection
/// @param name Name of the collection
@@ -65,9 +65,9 @@
return 0x0000000000000000000000000000000000000000;
}
- /// @dev EVM selector for this function is: 0xd1df968c,
- /// or in textual repr: createERC721MetadataNFTCollection(string,string,string,string)
- function createERC721MetadataNFTCollection(
+ /// @dev EVM selector for this function is: 0xa9e7b5c0,
+ /// or in textual repr: createERC721MetadataCompatibleNFTCollection(string,string,string,string)
+ function createERC721MetadataCompatibleNFTCollection(
string memory name,
string memory description,
string memory tokenPrefix,
@@ -112,9 +112,9 @@
return 0x0000000000000000000000000000000000000000;
}
- /// @dev EVM selector for this function is: 0xbea6a299,
- /// or in textual repr: createERC721MetadataRFTCollection(string,string,string,string)
- function createERC721MetadataRFTCollection(
+ /// @dev EVM selector for this function is: 0xa5596388,
+ /// or in textual repr: createERC721MetadataCompatibleRFTCollection(string,string,string,string)
+ function createERC721MetadataCompatibleRFTCollection(
string memory name,
string memory description,
string memory tokenPrefix,
tests/src/eth/api/CollectionHelpers.soldiffbeforeafterboth--- a/tests/src/eth/api/CollectionHelpers.sol
+++ b/tests/src/eth/api/CollectionHelpers.sol
@@ -18,7 +18,7 @@
}
/// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0xf62c7aa9
+/// @dev the ERC-165 identifier for this interface is 0x95eb98f4
interface CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
/// Create an NFT collection
/// @param name Name of the collection
@@ -46,9 +46,9 @@
string memory tokenPrefix
) external payable returns (address);
- /// @dev EVM selector for this function is: 0xd1df968c,
- /// or in textual repr: createERC721MetadataNFTCollection(string,string,string,string)
- function createERC721MetadataNFTCollection(
+ /// @dev EVM selector for this function is: 0xa9e7b5c0,
+ /// or in textual repr: createERC721MetadataCompatibleNFTCollection(string,string,string,string)
+ function createERC721MetadataCompatibleNFTCollection(
string memory name,
string memory description,
string memory tokenPrefix,
@@ -71,9 +71,9 @@
string memory tokenPrefix
) external payable returns (address);
- /// @dev EVM selector for this function is: 0xbea6a299,
- /// or in textual repr: createERC721MetadataRFTCollection(string,string,string,string)
- function createERC721MetadataRFTCollection(
+ /// @dev EVM selector for this function is: 0xa5596388,
+ /// or in textual repr: createERC721MetadataCompatibleRFTCollection(string,string,string,string)
+ function createERC721MetadataCompatibleRFTCollection(
string memory name,
string memory description,
string memory tokenPrefix,
tests/src/eth/collectionHelpersAbi.jsondiffbeforeafterboth--- a/tests/src/eth/collectionHelpersAbi.json
+++ b/tests/src/eth/collectionHelpersAbi.json
@@ -32,7 +32,7 @@
{ "internalType": "string", "name": "tokenPrefix", "type": "string" },
{ "internalType": "string", "name": "baseUri", "type": "string" }
],
- "name": "createERC721MetadataNFTCollection",
+ "name": "createERC721MetadataCompatibleNFTCollection",
"outputs": [{ "internalType": "address", "name": "", "type": "address" }],
"stateMutability": "payable",
"type": "function"
@@ -44,7 +44,7 @@
{ "internalType": "string", "name": "tokenPrefix", "type": "string" },
{ "internalType": "string", "name": "baseUri", "type": "string" }
],
- "name": "createERC721MetadataRFTCollection",
+ "name": "createERC721MetadataCompatibleRFTCollection",
"outputs": [{ "internalType": "address", "name": "", "type": "address" }],
"stateMutability": "payable",
"type": "function"
tests/src/eth/collectionProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionProperties.test.ts
+++ b/tests/src/eth/collectionProperties.test.ts
@@ -14,7 +14,7 @@
itEth('Can be set', async({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const collection = await helper.nft.mintCollection(alice, {name: 'name', description: 'test', tokenPrefix: 'test'});
+ const collection = await helper.nft.mintCollection(alice, {name: 'name', description: 'test', tokenPrefix: 'test', properties: []});
await collection.addAdmin(alice, {Ethereum: caller});
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
@@ -24,7 +24,7 @@
const raw = (await collection.getData())?.raw;
- expect(raw.properties[1].value).to.equal('testValue');
+ expect(raw.properties[0].value).to.equal('testValue');
});
itEth('Can be deleted', async({helper}) => {
tests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -97,7 +97,7 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelpers.methods.createERC721MetadataNFTCollection('Sponsor collection', '1', '1', '').send({value: Number(2n * nominal)});
+ let result = await collectionHelpers.methods.createERC721MetadataCompatibleNFTCollection('Sponsor collection', '1', '1', '').send({value: Number(2n * nominal)});
const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
const collectionId = helper.ethAddress.extractCollectionId(collectionIdAddress);
const collection = helper.nft.getCollectionObject(collectionId);
@@ -167,7 +167,7 @@
// itWeb3('Sponsoring collection from substrate address via access list', async ({api, web3, privateKeyWrapper}) => {
// const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
// const collectionHelpers = evmCollectionHelpers(web3, owner);
- // const result = await collectionHelpers.methods.createERC721MetadataNFTCollection('Sponsor collection', '1', '1', '').send();
+ // const result = await collectionHelpers.methods.createERC721MetadataCompatibleNFTCollection('Sponsor collection', '1', '1', '').send();
// const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
// const sponsor = privateKeyWrapper('//Alice');
// const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
@@ -223,7 +223,7 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelpers.methods.createERC721MetadataNFTCollection('Sponsor collection', '1', '1', '').send({value: Number(2n * nominal)});
+ let result = await collectionHelpers.methods.createERC721MetadataCompatibleNFTCollection('Sponsor collection', '1', '1', '').send({value: Number(2n * nominal)});
const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
const collectionId = helper.ethAddress.extractCollectionId(collectionIdAddress);
const collection = helper.nft.getCollectionObject(collectionId);
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -83,14 +83,12 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelper.methods.createERC721MetadataNFTCollection('Mint collection', 'a', 'b', tokenPrefix).send({value: Number(2n * helper.balance.getOneTokenNominal())});
- const collectionAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Mint collection', 'a', 'b', tokenPrefix);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
const nextTokenId = await contract.methods.nextTokenId().call();
expect(nextTokenId).to.be.equal('1');
- result = await contract.methods.mint(
+ const result = await contract.methods.mint(
receiver,
nextTokenId,
).send();
@@ -115,7 +113,7 @@
});
itEth('TokenURI from url', async ({helper}) => {
- const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'url', 'Token URI');
+ const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URI', 'Token URI');
expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');
});
@@ -126,7 +124,7 @@
itEth('TokenURI from baseURI + suffix', async ({helper}) => {
const suffix = '/some/suffix';
- const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'suffix', suffix);
+ const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URISuffix', suffix);
expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);
});
});
@@ -146,7 +144,7 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createERC721MetadataNFTCollection(owner, 'Mint collection', '6', '6', '');
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Mint collection', '6', '6', '');
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
const nextTokenId = await contract.methods.nextTokenId().call();
tests/src/eth/proxy/nonFungibleProxy.test.tsdiffbeforeafterboth--- a/tests/src/eth/proxy/nonFungibleProxy.test.ts
+++ b/tests/src/eth/proxy/nonFungibleProxy.test.ts
@@ -101,7 +101,7 @@
itEth('Can perform mint()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createERC721MetadataNFTCollection(owner, 'A', 'A', 'A', '');
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'A', 'A', 'A', '');
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
tests/src/eth/reFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -124,7 +124,7 @@
itEth('Can perform mint()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createERC721MetadataRFTCollection(owner, 'Minty', '6', '6', '');
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Minty', '6', '6', '');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
const nextTokenId = await contract.methods.nextTokenId().call();
@@ -147,7 +147,7 @@
itEth('Can perform mintBulk()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createERC721MetadataRFTCollection(owner, 'MintBulky', '6', '6', '');
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'MintBulky', '6', '6', '');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
{
tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -80,14 +80,12 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelper.methods.createERC721MetadataNFTCollection('Mint collection', 'a', 'b', tokenPrefix).send({value: Number(2n * helper.balance.getOneTokenNominal())});
- const collectionAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Mint collection', 'a', 'b', tokenPrefix);
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
const nextTokenId = await contract.methods.nextTokenId().call();
expect(nextTokenId).to.be.equal('1');
- result = await contract.methods.mint(
+ const result = await contract.methods.mint(
receiver,
nextTokenId,
).send();
@@ -112,7 +110,7 @@
});
itEth('TokenURI from url', async ({helper}) => {
- const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'url', 'Token URI');
+ const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URI', 'Token URI');
expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');
});
@@ -123,7 +121,7 @@
itEth('TokenURI from baseURI + suffix', async ({helper}) => {
const suffix = '/some/suffix';
- const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'suffix', suffix);
+ const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URISuffix', suffix);
expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);
});
});
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable function-call-argument-newline */5// eslint-disable-next-line @typescript-eslint/triple-slash-reference6/// <reference path="unique.dev.d.ts" />78import {readFile} from 'fs/promises';910import Web3 from 'web3';11import {WebsocketProvider} from 'web3-core';12import {Contract} from 'web3-eth-contract';1314import * as solc from 'solc';1516import {evmToAddress} from '@polkadot/util-crypto';17import {IKeyringPair} from '@polkadot/types/types';1819import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';2021import {ContractImports, CompiledContract, NormalizedEvent} from './types';2223// Native contracts ABI24import collectionHelpersAbi from '../../collectionHelpersAbi.json';25import fungibleAbi from '../../fungibleAbi.json';26import nonFungibleAbi from '../../nonFungibleAbi.json';27import refungibleAbi from '../../reFungibleAbi.json';28import refungibleTokenAbi from '../../reFungibleTokenAbi.json';29import contractHelpersAbi from './../contractHelpersAbi.json';30import {ICrossAccountId, TEthereumAccount} from '../../../util/playgrounds/types';3132class EthGroupBase {33 helper: EthUniqueHelper;3435 constructor(helper: EthUniqueHelper) {36 this.helper = helper;37 }38}394041class ContractGroup extends EthGroupBase {42 async findImports(imports?: ContractImports[]){43 if(!imports) return function(path: string) {44 return {error: `File not found: ${path}`};45 };46 47 const knownImports = {} as {[key: string]: string};48 for(const imp of imports) {49 knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();50 }51 52 return function(path: string) {53 if(path in knownImports) return {contents: knownImports[path]};54 return {error: `File not found: ${path}`};55 };56 }5758 async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {59 const out = JSON.parse(solc.compile(JSON.stringify({60 language: 'Solidity',61 sources: {62 [`${name}.sol`]: {63 content: src,64 },65 },66 settings: {67 outputSelection: {68 '*': {69 '*': ['*'],70 },71 },72 },73 }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];74 75 return {76 abi: out.abi,77 object: '0x' + out.evm.bytecode.object,78 };79 }8081 async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[]): Promise<Contract> {82 const compiledContract = await this.compile(name, src, imports);83 return this.deployByAbi(signer, compiledContract.abi, compiledContract.object);84 }8586 async deployByAbi(signer: string, abi: any, object: string): Promise<Contract> {87 const web3 = this.helper.getWeb3();88 const contract = new web3.eth.Contract(abi, undefined, {89 data: object,90 from: signer,91 gas: this.helper.eth.DEFAULT_GAS,92 });93 return await contract.deploy({data: object}).send({from: signer});94 }9596}97 98class NativeContractGroup extends EthGroupBase {99100 contractHelpers(caller: string): Contract {101 const web3 = this.helper.getWeb3();102 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.helper.eth.DEFAULT_GAS});103 }104105 collectionHelpers(caller: string) {106 const web3 = this.helper.getWeb3();107 return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});108 }109110 collection(address: string, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {111 const abi = {112 'nft': nonFungibleAbi,113 'rft': refungibleAbi,114 'ft': fungibleAbi,115 }[mode];116 const web3 = this.helper.getWeb3();117 return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});118 }119120 collectionById(collectionId: number, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {121 return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller);122 }123124 rftToken(address: string, caller?: string): Contract {125 const web3 = this.helper.getWeb3();126 return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});127 }128129 rftTokenById(collectionId: number, tokenId: number, caller?: string): Contract {130 return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);131 }132}133134135class EthGroup extends EthGroupBase {136 DEFAULT_GAS = 2_500_000;137138 createAccount() {139 const web3 = this.helper.getWeb3();140 const account = web3.eth.accounts.create();141 web3.eth.accounts.wallet.add(account.privateKey);142 return account.address;143 }144145 async createAccountWithBalance(donor: IKeyringPair, amount=1000n) {146 const account = this.createAccount();147 await this.transferBalanceFromSubstrate(donor, account, amount);148 149 return account;150 }151152 async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=1000n, inTokens=true) {153 return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));154 }155 156 async getCollectionCreationFee(signer: string) {157 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);158 return await collectionHelper.methods.collectionCreationFee().call();159 }160161 async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {162 if(!gasLimit) gasLimit = this.DEFAULT_GAS;163 const web3 = this.helper.getWeb3();164 const gasPrice = await web3.eth.getGasPrice();165 // TODO: check execution status166 await this.helper.executeExtrinsic(167 signer,168 'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],169 true,170 );171 }172173 async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {174 return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);175 }176177 async createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {178 const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();179 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);180 181 const result = await collectionHelper.methods.createNFTCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});182183 const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);184 const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);185186 return {collectionId, collectionAddress};187 }188189 async createERC721MetadataNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string}> {190 const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();191 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);192 193 const result = await collectionHelper.methods.createERC721MetadataNFTCollection(name, description, tokenPrefix, baseUri).send({value: Number(collectionCreationPrice)});194195 const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);196 const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);197198 return {collectionId, collectionAddress};199 }200201 async createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {202 const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();203 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);204 205 const result = await collectionHelper.methods.createRFTCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});206207 const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);208 const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);209210 return {collectionId, collectionAddress};211 }212213 async createERC721MetadataRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string}> {214 const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();215 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);216 217 const result = await collectionHelper.methods.createERC721MetadataRFTCollection(name, description, tokenPrefix, baseUri).send({value: Number(collectionCreationPrice)});218219 const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);220 const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);221222 return {collectionId, collectionAddress};223 }224225 async deployCollectorContract(signer: string): Promise<Contract> {226 return await this.helper.ethContract.deployByCode(signer, 'Collector', `227 // SPDX-License-Identifier: UNLICENSED228 pragma solidity ^0.8.6;229230 contract Collector {231 uint256 collected;232 fallback() external payable {233 giveMoney();234 }235 function giveMoney() public payable {236 collected += msg.value;237 }238 function getCollected() public view returns (uint256) {239 return collected;240 }241 function getUnaccounted() public view returns (uint256) {242 return address(this).balance - collected;243 }244245 function withdraw(address payable target) public {246 target.transfer(collected);247 collected = 0;248 }249 }250 `);251 }252253 async deployFlipper(signer: string): Promise<Contract> {254 return await this.helper.ethContract.deployByCode(signer, 'Flipper', `255 // SPDX-License-Identifier: UNLICENSED256 pragma solidity ^0.8.6;257258 contract Flipper {259 bool value = false;260 function flip() public {261 value = !value;262 }263 function getValue() public view returns (bool) {264 return value;265 }266 }267 `);268 }269270 async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {271 const before = await this.helper.balance.getEthereum(user);272 await call();273 // In dev mode, the transaction might not finish processing in time274 await this.helper.wait.newBlocks(1);275 const after = await this.helper.balance.getEthereum(user);276277 return before - after;278 }279280 normalizeEvents(events: any): NormalizedEvent[] {281 const output = [];282 for (const key of Object.keys(events)) {283 if (key.match(/^[0-9]+$/)) {284 output.push(events[key]);285 } else if (Array.isArray(events[key])) {286 output.push(...events[key]);287 } else {288 output.push(events[key]);289 }290 }291 output.sort((a, b) => a.logIndex - b.logIndex);292 return output.map(({address, event, returnValues}) => {293 const args: { [key: string]: string } = {};294 for (const key of Object.keys(returnValues)) {295 if (!key.match(/^[0-9]+$/)) {296 args[key] = returnValues[key];297 }298 }299 return {300 address,301 event,302 args,303 };304 });305 }306307 async calculateFee(address: ICrossAccountId, code: () => Promise<any>): Promise<bigint> {308 const wrappedCode = async () => {309 await code();310 // In dev mode, the transaction might not finish processing in time311 await this.helper.wait.newBlocks(1);312 };313 return await this.helper.arrange.calculcateFee(address, wrappedCode);314 }315} 316317class EthAddressGroup extends EthGroupBase {318 extractCollectionId(address: string): number {319 if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');320 return parseInt(address.substr(address.length - 8), 16);321 }322323 fromCollectionId(collectionId: number): string {324 if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');325 return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8,'0')}`);326 }327328 extractTokenId(address: string): {collectionId: number, tokenId: number} {329 if (!address.startsWith('0x'))330 throw 'address not starts with "0x"';331 if (address.length > 42)332 throw 'address length is more than 20 bytes';333 return {334 collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),335 tokenId: Number('0x' + address.substring(address.length - 8)),336 };337 }338339 fromTokenId(collectionId: number, tokenId: number): string {340 return this.helper.util.getTokenAddress({collectionId, tokenId});341 }342343 normalizeAddress(address: string): string {344 return '0x' + address.substring(address.length - 40);345 }346} 347 348export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;349350export class EthUniqueHelper extends DevUniqueHelper {351 web3: Web3 | null = null;352 web3Provider: WebsocketProvider | null = null;353354 eth: EthGroup;355 ethAddress: EthAddressGroup;356 ethNativeContract: NativeContractGroup;357 ethContract: ContractGroup;358359 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {360 options.helperBase = options.helperBase ?? EthUniqueHelper;361362 super(logger, options);363 this.eth = new EthGroup(this);364 this.ethAddress = new EthAddressGroup(this);365 this.ethNativeContract = new NativeContractGroup(this);366 this.ethContract = new ContractGroup(this);367 }368369 getWeb3(): Web3 {370 if(this.web3 === null) throw Error('Web3 not connected');371 return this.web3;372 }373374 async connectWeb3(wsEndpoint: string) {375 if(this.web3 !== null) return;376 this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);377 this.web3 = new Web3(this.web3Provider);378 }379380 async disconnect() {381 if(this.web3 === null) return;382 this.web3Provider?.connection.close();383384 await super.disconnect();385 }386387 clearApi() {388 this.web3 = null;389 }390391 clone(helperCls: EthUniqueHelperConstructor, options?: { [key: string]: any; }): EthUniqueHelper {392 const newHelper = super.clone(helperCls, options) as EthUniqueHelper;393 newHelper.web3 = this.web3;394 newHelper.web3Provider = this.web3Provider;395396 return newHelper;397 }398}399 1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable function-call-argument-newline */5// eslint-disable-next-line @typescript-eslint/triple-slash-reference6/// <reference path="unique.dev.d.ts" />78import {readFile} from 'fs/promises';910import Web3 from 'web3';11import {WebsocketProvider} from 'web3-core';12import {Contract} from 'web3-eth-contract';1314import * as solc from 'solc';1516import {evmToAddress} from '@polkadot/util-crypto';17import {IKeyringPair} from '@polkadot/types/types';1819import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';2021import {ContractImports, CompiledContract, NormalizedEvent} from './types';2223// Native contracts ABI24import collectionHelpersAbi from '../../collectionHelpersAbi.json';25import fungibleAbi from '../../fungibleAbi.json';26import nonFungibleAbi from '../../nonFungibleAbi.json';27import refungibleAbi from '../../reFungibleAbi.json';28import refungibleTokenAbi from '../../reFungibleTokenAbi.json';29import contractHelpersAbi from './../contractHelpersAbi.json';30import {ICrossAccountId, TEthereumAccount} from '../../../util/playgrounds/types';3132class EthGroupBase {33 helper: EthUniqueHelper;3435 constructor(helper: EthUniqueHelper) {36 this.helper = helper;37 }38}394041class ContractGroup extends EthGroupBase {42 async findImports(imports?: ContractImports[]){43 if(!imports) return function(path: string) {44 return {error: `File not found: ${path}`};45 };46 47 const knownImports = {} as {[key: string]: string};48 for(const imp of imports) {49 knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();50 }51 52 return function(path: string) {53 if(path in knownImports) return {contents: knownImports[path]};54 return {error: `File not found: ${path}`};55 };56 }5758 async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {59 const out = JSON.parse(solc.compile(JSON.stringify({60 language: 'Solidity',61 sources: {62 [`${name}.sol`]: {63 content: src,64 },65 },66 settings: {67 outputSelection: {68 '*': {69 '*': ['*'],70 },71 },72 },73 }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];74 75 return {76 abi: out.abi,77 object: '0x' + out.evm.bytecode.object,78 };79 }8081 async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[]): Promise<Contract> {82 const compiledContract = await this.compile(name, src, imports);83 return this.deployByAbi(signer, compiledContract.abi, compiledContract.object);84 }8586 async deployByAbi(signer: string, abi: any, object: string): Promise<Contract> {87 const web3 = this.helper.getWeb3();88 const contract = new web3.eth.Contract(abi, undefined, {89 data: object,90 from: signer,91 gas: this.helper.eth.DEFAULT_GAS,92 });93 return await contract.deploy({data: object}).send({from: signer});94 }9596}97 98class NativeContractGroup extends EthGroupBase {99100 contractHelpers(caller: string): Contract {101 const web3 = this.helper.getWeb3();102 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.helper.eth.DEFAULT_GAS});103 }104105 collectionHelpers(caller: string) {106 const web3 = this.helper.getWeb3();107 return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});108 }109110 collection(address: string, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {111 const abi = {112 'nft': nonFungibleAbi,113 'rft': refungibleAbi,114 'ft': fungibleAbi,115 }[mode];116 const web3 = this.helper.getWeb3();117 return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});118 }119120 collectionById(collectionId: number, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {121 return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller);122 }123124 rftToken(address: string, caller?: string): Contract {125 const web3 = this.helper.getWeb3();126 return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});127 }128129 rftTokenById(collectionId: number, tokenId: number, caller?: string): Contract {130 return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);131 }132}133134135class EthGroup extends EthGroupBase {136 DEFAULT_GAS = 2_500_000;137138 createAccount() {139 const web3 = this.helper.getWeb3();140 const account = web3.eth.accounts.create();141 web3.eth.accounts.wallet.add(account.privateKey);142 return account.address;143 }144145 async createAccountWithBalance(donor: IKeyringPair, amount=1000n) {146 const account = this.createAccount();147 await this.transferBalanceFromSubstrate(donor, account, amount);148 149 return account;150 }151152 async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=1000n, inTokens=true) {153 return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));154 }155 156 async getCollectionCreationFee(signer: string) {157 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);158 return await collectionHelper.methods.collectionCreationFee().call();159 }160161 async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {162 if(!gasLimit) gasLimit = this.DEFAULT_GAS;163 const web3 = this.helper.getWeb3();164 const gasPrice = await web3.eth.getGasPrice();165 // TODO: check execution status166 await this.helper.executeExtrinsic(167 signer,168 'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],169 true,170 );171 }172173 async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {174 return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);175 }176177 async createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {178 const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();179 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);180 181 const result = await collectionHelper.methods.createNFTCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});182183 const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);184 const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);185186 return {collectionId, collectionAddress};187 }188189 async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string}> {190 const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();191 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);192 193 const result = await collectionHelper.methods.createERC721MetadataCompatibleNFTCollection(name, description, tokenPrefix, baseUri).send({value: Number(collectionCreationPrice)});194195 const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);196 const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);197198 return {collectionId, collectionAddress};199 }200201 async createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {202 const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();203 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);204 205 const result = await collectionHelper.methods.createRFTCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});206207 const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);208 const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);209210 return {collectionId, collectionAddress};211 }212213 async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string}> {214 const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();215 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);216 217 const result = await collectionHelper.methods.createERC721MetadataCompatibleRFTCollection(name, description, tokenPrefix, baseUri).send({value: Number(collectionCreationPrice)});218219 const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);220 const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);221222 return {collectionId, collectionAddress};223 }224225 async deployCollectorContract(signer: string): Promise<Contract> {226 return await this.helper.ethContract.deployByCode(signer, 'Collector', `227 // SPDX-License-Identifier: UNLICENSED228 pragma solidity ^0.8.6;229230 contract Collector {231 uint256 collected;232 fallback() external payable {233 giveMoney();234 }235 function giveMoney() public payable {236 collected += msg.value;237 }238 function getCollected() public view returns (uint256) {239 return collected;240 }241 function getUnaccounted() public view returns (uint256) {242 return address(this).balance - collected;243 }244245 function withdraw(address payable target) public {246 target.transfer(collected);247 collected = 0;248 }249 }250 `);251 }252253 async deployFlipper(signer: string): Promise<Contract> {254 return await this.helper.ethContract.deployByCode(signer, 'Flipper', `255 // SPDX-License-Identifier: UNLICENSED256 pragma solidity ^0.8.6;257258 contract Flipper {259 bool value = false;260 function flip() public {261 value = !value;262 }263 function getValue() public view returns (bool) {264 return value;265 }266 }267 `);268 }269270 async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {271 const before = await this.helper.balance.getEthereum(user);272 await call();273 // In dev mode, the transaction might not finish processing in time274 await this.helper.wait.newBlocks(1);275 const after = await this.helper.balance.getEthereum(user);276277 return before - after;278 }279280 normalizeEvents(events: any): NormalizedEvent[] {281 const output = [];282 for (const key of Object.keys(events)) {283 if (key.match(/^[0-9]+$/)) {284 output.push(events[key]);285 } else if (Array.isArray(events[key])) {286 output.push(...events[key]);287 } else {288 output.push(events[key]);289 }290 }291 output.sort((a, b) => a.logIndex - b.logIndex);292 return output.map(({address, event, returnValues}) => {293 const args: { [key: string]: string } = {};294 for (const key of Object.keys(returnValues)) {295 if (!key.match(/^[0-9]+$/)) {296 args[key] = returnValues[key];297 }298 }299 return {300 address,301 event,302 args,303 };304 });305 }306307 async calculateFee(address: ICrossAccountId, code: () => Promise<any>): Promise<bigint> {308 const wrappedCode = async () => {309 await code();310 // In dev mode, the transaction might not finish processing in time311 await this.helper.wait.newBlocks(1);312 };313 return await this.helper.arrange.calculcateFee(address, wrappedCode);314 }315} 316317class EthAddressGroup extends EthGroupBase {318 extractCollectionId(address: string): number {319 if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');320 return parseInt(address.substr(address.length - 8), 16);321 }322323 fromCollectionId(collectionId: number): string {324 if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');325 return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8,'0')}`);326 }327328 extractTokenId(address: string): {collectionId: number, tokenId: number} {329 if (!address.startsWith('0x'))330 throw 'address not starts with "0x"';331 if (address.length > 42)332 throw 'address length is more than 20 bytes';333 return {334 collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),335 tokenId: Number('0x' + address.substring(address.length - 8)),336 };337 }338339 fromTokenId(collectionId: number, tokenId: number): string {340 return this.helper.util.getTokenAddress({collectionId, tokenId});341 }342343 normalizeAddress(address: string): string {344 return '0x' + address.substring(address.length - 40);345 }346} 347 348export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;349350export class EthUniqueHelper extends DevUniqueHelper {351 web3: Web3 | null = null;352 web3Provider: WebsocketProvider | null = null;353354 eth: EthGroup;355 ethAddress: EthAddressGroup;356 ethNativeContract: NativeContractGroup;357 ethContract: ContractGroup;358359 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {360 options.helperBase = options.helperBase ?? EthUniqueHelper;361362 super(logger, options);363 this.eth = new EthGroup(this);364 this.ethAddress = new EthAddressGroup(this);365 this.ethNativeContract = new NativeContractGroup(this);366 this.ethContract = new ContractGroup(this);367 }368369 getWeb3(): Web3 {370 if(this.web3 === null) throw Error('Web3 not connected');371 return this.web3;372 }373374 async connectWeb3(wsEndpoint: string) {375 if(this.web3 !== null) return;376 this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);377 this.web3 = new Web3(this.web3Provider);378 }379380 async disconnect() {381 if(this.web3 === null) return;382 this.web3Provider?.connection.close();383384 await super.disconnect();385 }386387 clearApi() {388 this.web3 = null;389 }390391 clone(helperCls: EthUniqueHelperConstructor, options?: { [key: string]: any; }): EthUniqueHelper {392 const newHelper = super.clone(helperCls, options) as EthUniqueHelper;393 newHelper.web3 = this.web3;394 newHelper.web3Provider = this.web3Provider;395396 return newHelper;397 }398}399