git.delta.rocks / unique-network / refs/commits / e6b5df49e9b9

difftreelog

test ethContract group for eth-playgrounds

Andrey2022-09-04parent: #a68b33e.patch.diff
in: master

5 files changed

modifiedtests/package.jsondiffbeforeafterboth
30 "testEth": "mocha --timeout 9999999 -r ts-node/register './**/eth/**/*.test.ts'",30 "testEth": "mocha --timeout 9999999 -r ts-node/register './**/eth/**/*.test.ts'",
31 "testEthMarketplace": "mocha --timeout 9999999 -r ts-node/register './**/eth/marketplace/**/*.test.ts'",31 "testEthMarketplace": "mocha --timeout 9999999 -r ts-node/register './**/eth/marketplace/**/*.test.ts'",
32 "testEthNesting": "mocha --timeout 9999999 -r ts-node/register './**/eth/nesting/**/*.test.ts'",32 "testEthNesting": "mocha --timeout 9999999 -r ts-node/register './**/eth/nesting/**/*.test.ts'",
33 "testEthPayable": "mocha --timeout 9999999 -r ts-node/register './**/eth/payable.test.ts'",
33 "load": "mocha --timeout 9999999 -r ts-node/register './**/*.load.ts'",34 "load": "mocha --timeout 9999999 -r ts-node/register './**/*.load.ts'",
34 "loadTransfer": "ts-node src/transfer.nload.ts",35 "loadTransfer": "ts-node src/transfer.nload.ts",
35 "testCollision": "mocha --timeout 9999999 -r ts-node/register ./src/collision-tests/*.test.ts",36 "testCollision": "mocha --timeout 9999999 -r ts-node/register ./src/collision-tests/*.test.ts",
modifiedtests/src/eth/payable.test.tsdiffbeforeafterboth
14// You should have received a copy of the GNU General Public License14// You should have received a copy of the GNU General Public License
15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
1616
17import {expect} from 'chai';
18import {submitTransactionAsync} from '../substrate/substrate-api';17import {IKeyringPair} from '@polkadot/types/types';
18
19import {createEthAccountWithBalance, deployCollector, GAS_ARGS, itWeb3, subToEth, transferBalanceToEth} from './util/helpers';19import {itEth, expect, usingEthPlaygrounds} from './util/playgrounds';
20import {evmToAddress} from '@polkadot/util-crypto';
21import {getGenericResult, UNIQUE} from '../util/helpers';
22import {getBalanceSingle, transferBalanceExpectSuccess} from '../substrate/get-balance';
2320
24describe('EVM payable contracts', () => {21describe('EVM payable contracts', () => {
22 let donor: IKeyringPair;
23
24 before(async function() {
25 await usingEthPlaygrounds(async (helper, privateKey) => {
26 donor = privateKey('//Alice');
27 });
28 });
29
25 itWeb3('Evm contract can receive wei from eth account', async ({api, web3, privateKeyWrapper}) => {30 itEth('Evm contract can receive wei from eth account', async ({helper}) => {
26 const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);31 const deployer = await helper.eth.createAccountWithBalance(donor);
27 const contract = await deployCollector(web3, deployer);32 const contract = await helper.eth.deployCollectorContract(deployer);
33
34 const web3 = helper.getWeb3();
2835
29 await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: '10000', ...GAS_ARGS});36 await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: '10000', gas: helper.eth.DEFAULT_GAS});
3037
31 expect(await contract.methods.getCollected().call()).to.be.equal('10000');38 expect(await contract.methods.getCollected().call()).to.be.equal('10000');
32 });39 });
3340
34 itWeb3('Evm contract can receive wei from substrate account', async ({api, web3, privateKeyWrapper}) => {41 itEth('Evm contract can receive wei from substrate account', async ({helper}) => {
35 const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);42 const deployer = await helper.eth.createAccountWithBalance(donor);
36 const contract = await deployCollector(web3, deployer);43 const contract = await helper.eth.deployCollectorContract(deployer);
37 const alice = privateKeyWrapper('//Alice');44 const [alice] = await helper.arrange.createAccounts([10n], donor);
45
46 const weiCount = '10000';
3847
39 // Transaction fee/value will be payed from subToEth(sender) evm balance,48 // Transaction fee/value will be payed from subToEth(sender) evm balance,
40 // which is backed by evmToAddress(subToEth(sender)) substrate balance49 // which is backed by evmToAddress(subToEth(sender)) substrate balance
41 await transferBalanceToEth(api, alice, subToEth(alice.address));50 await helper.eth.transferBalanceFromSubstrate(alice, helper.address.substrateToEth(alice.address), 5n);
4251
43 {52
44 const tx = api.tx.evm.call(53 await helper.eth.callEVM(alice, contract.options.address, contract.methods.giveMoney().encodeABI(), weiCount);
45 subToEth(alice.address),
46 contract.options.address,
47 contract.methods.giveMoney().encodeABI(),
52 null,
53 [],
54 );
55 const events = await submitTransactionAsync(alice, tx);
56 const result = getGenericResult(events);
57 expect(result.success).to.be.true;
58 }
5954
60 expect(await contract.methods.getCollected().call()).to.be.equal('10000');55 expect(await contract.methods.getCollected().call()).to.be.equal(weiCount);
61 });56 });
6257
63 // We can't handle sending balance to backing storage of evm balance, because evmToAddress operation is irreversible58 // We can't handle sending balance to backing storage of evm balance, because evmToAddress operation is irreversible
64 itWeb3('Wei sent directly to backing storage of evm contract balance is unaccounted', async({api, web3, privateKeyWrapper}) => {59 itEth('Wei sent directly to backing storage of evm contract balance is unaccounted', async({helper}) => {
65 const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);60 const deployer = await helper.eth.createAccountWithBalance(donor);
66 const contract = await deployCollector(web3, deployer);61 const contract = await helper.eth.deployCollectorContract(deployer);
67 const alice = privateKeyWrapper('//Alice');62 const [alice] = await helper.arrange.createAccounts([10n], donor);
63
64 const weiCount = 10_000n;
6865
69 await transferBalanceExpectSuccess(api, alice, evmToAddress(contract.options.address), '10000');66 await helper.eth.transferBalanceFromSubstrate(alice, contract.options.address, weiCount, false);
7067
71 expect(await contract.methods.getUnaccounted().call()).to.be.equal('10000');68 expect(await contract.methods.getUnaccounted().call()).to.be.equal(weiCount.toString());
72 });69 });
7370
74 itWeb3('Balance can be retrieved from evm contract', async({api, web3, privateKeyWrapper}) => {71 itEth('Balance can be retrieved from evm contract', async({helper, privateKey}) => {
75 const FEE_BALANCE = 1000n * UNIQUE;72 const FEE_BALANCE = 10n * helper.balance.getOneTokenNominal();
76 const CONTRACT_BALANCE = 1n * UNIQUE;73 const CONTRACT_BALANCE = 1n * helper.balance.getOneTokenNominal();
7774
78 const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);75 const deployer = await helper.eth.createAccountWithBalance(donor);
79 const contract = await deployCollector(web3, deployer);76 const contract = await helper.eth.deployCollectorContract(deployer);
80 const alice = privateKeyWrapper('//Alice');77 const [alice] = await helper.arrange.createAccounts([20n], donor);
78
79 const web3 = helper.getWeb3();
8180
82 await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: CONTRACT_BALANCE.toString(), ...GAS_ARGS});81 await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: CONTRACT_BALANCE.toString(), gas: helper.eth.DEFAULT_GAS});
8382
84 const receiver = privateKeyWrapper(`//Receiver${Date.now()}`);83 const receiver = privateKey(`//Receiver${Date.now()}`);
8584
86 // First receive balance on eth balance of bob85 // First receive balance on eth balance of bob
87 {86 {
88 const ethReceiver = subToEth(receiver.address);87 const ethReceiver = helper.address.substrateToEth(receiver.address);
89 expect(await web3.eth.getBalance(ethReceiver)).to.be.equal('0');88 expect(await web3.eth.getBalance(ethReceiver)).to.be.equal('0');
90 await contract.methods.withdraw(ethReceiver).send({from: deployer});89 await contract.methods.withdraw(ethReceiver).send({from: deployer});
91 expect(await web3.eth.getBalance(ethReceiver)).to.be.equal(CONTRACT_BALANCE.toString());90 expect(await web3.eth.getBalance(ethReceiver)).to.be.equal(CONTRACT_BALANCE.toString());
92 }91 }
9392
94 // Some balance is required to pay fee for evm.withdraw call93 // Some balance is required to pay fee for evm.withdraw call
95 await transferBalanceExpectSuccess(api, alice, receiver.address, FEE_BALANCE.toString());94 await helper.balance.transferToSubstrate(alice, receiver.address, FEE_BALANCE);
95 // await transferBalanceExpectSuccess(api, alice, receiver.address, FEE_BALANCE.toString());
9696
97 // Withdraw balance from eth to substrate97 // Withdraw balance from eth to substrate
98 {98 {
99 const initialReceiverBalance = await getBalanceSingle(api, receiver.address);99 const initialReceiverBalance = await helper.balance.getSubstrate(receiver.address);
100 const tx = api.tx.evm.withdraw(100 await helper.executeExtrinsic(receiver, 'api.tx.evm.withdraw', [helper.address.substrateToEth(receiver.address), CONTRACT_BALANCE.toString()], true);
101 subToEth(receiver.address),
102 CONTRACT_BALANCE.toString(),
103 );
104 const events = await submitTransactionAsync(receiver, tx);
105 const result = getGenericResult(events);
106 expect(result.success).to.be.true;
107 const finalReceiverBalance = await getBalanceSingle(api, receiver.address);101 const finalReceiverBalance = await helper.balance.getSubstrate(receiver.address);
108102
109 expect(finalReceiverBalance > initialReceiverBalance).to.be.true;103 expect(finalReceiverBalance > initialReceiverBalance).to.be.true;
110 }104 }
addedtests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth

no changes

modifiedtests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth
33
4/* eslint-disable function-call-argument-newline */4/* eslint-disable function-call-argument-newline */
5
6import {readFile} from 'fs/promises';
57
6import Web3 from 'web3';8import Web3 from 'web3';
7import {WebsocketProvider} from 'web3-core';9import {WebsocketProvider} from 'web3-core';
8import {Contract} from 'web3-eth-contract';10import {Contract} from 'web3-eth-contract';
11
12import * as solc from 'solc';
913
10import {evmToAddress} from '@polkadot/util-crypto';14import {evmToAddress} from '@polkadot/util-crypto';
11import {IKeyringPair} from '@polkadot/types/types';15import {IKeyringPair} from '@polkadot/types/types';
1216
13import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';17import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';
18
19import {ContractImports, CompiledContract} from './types';
1420
15// Native contracts ABI21// Native contracts ABI
16import collectionHelpersAbi from '../../collectionHelpersAbi.json';22import collectionHelpersAbi from '../../collectionHelpersAbi.json';
29}35}
30 36
31 37
38class ContractGroup extends EthGroupBase {
39 async findImports(imports?: ContractImports[]){
40 if(!imports) return function(path: string) {
41 return {error: 'File not found'};
42 };
43
44 const knownImports = {} as any;
45 for(let imp of imports) {
46 knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();
47 }
48
49 return function(path: string) {
50 if(knownImports.hasOwnProperty(path)) return {contents: knownImports[path]};
51 return {error: 'File not found'};
52 }
53 }
54
55 async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {
56 const out = JSON.parse(solc.compile(JSON.stringify({
57 language: 'Solidity',
58 sources: {
59 [`${name}.sol`]: {
60 content: src,
61 },
62 },
63 settings: {
64 outputSelection: {
65 '*': {
66 '*': ['*'],
67 },
68 },
69 },
70 }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];
71
72 return {
73 abi: out.abi,
74 object: '0x' + out.evm.bytecode.object,
75 };
76 }
77
78 async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[]): Promise<Contract> {
79 const compiledContract = await this.compile(name, src, imports);
80 return this.deployByAbi(signer, compiledContract.abi, compiledContract.object);
81 }
82
83 async deployByAbi(signer: string, abi: any, object: string): Promise<Contract> {
84 const web3 = this.helper.getWeb3();
85 const contract = new web3.eth.Contract(abi, undefined, {
86 data: object,
87 from: signer,
88 gas: this.helper.eth.DEFAULT_GAS
89 });
90 return await contract.deploy({data: object}).send({from: signer});
91 }
92
93}
94
32class NativeContractGroup extends EthGroupBase {95class NativeContractGroup extends EthGroupBase {
33 DEFAULT_GAS = 2_500_000;
3496
35 contractHelpers(caller: string): Contract {97 contractHelpers(caller: string): Contract {
36 const web3 = this.helper.getWeb3();98 const web3 = this.helper.getWeb3();
37 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.DEFAULT_GAS});99 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.helper.eth.DEFAULT_GAS});
38 }100 }
39101
40 collectionHelpers(caller: string) {102 collectionHelpers(caller: string) {
41 const web3 = this.helper.getWeb3();103 const web3 = this.helper.getWeb3();
42 return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.DEFAULT_GAS});104 return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});
43 }105 }
44106
45 collection(address: string, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {107 collection(address: string, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {
49 'ft': fungibleAbi111 'ft': fungibleAbi
50 }[mode];112 }[mode];
51 const web3 = this.helper.getWeb3();113 const web3 = this.helper.getWeb3();
52 return new web3.eth.Contract(abi as any, address, {gas: this.DEFAULT_GAS, ...(caller ? {from: caller} : {})});114 return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});
53 }115 }
54116
55 rftTokenByAddress(address: string, caller?: string): Contract {117 rftTokenByAddress(address: string, caller?: string): Contract {
56 const web3 = this.helper.getWeb3();118 const web3 = this.helper.getWeb3();
57 return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.DEFAULT_GAS, ...(caller ? {from: caller} : {})});119 return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});
58 }120 }
59121
60 rftToken(collectionId: number, tokenId: number, caller?: string): Contract {122 rftToken(collectionId: number, tokenId: number, caller?: string): Contract {
64126
65 127
66class EthGroup extends EthGroupBase {128class EthGroup extends EthGroupBase {
129 DEFAULT_GAS = 2_500_000;
130
67 createAccount() {131 createAccount() {
68 const web3 = this.helper.getWeb3();132 const web3 = this.helper.getWeb3();
78 return account;142 return account;
79 }143 }
80144
81 async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=1000n) {145 async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=1000n, inTokens=true) {
82 return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * this.helper.balance.getOneTokenNominal());146 return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));
83 }147 }
148
149 async callEVM(signer: IKeyringPair, contractAddress: string, abi: any, value: string, gasLimit?: number) {
150 if(!gasLimit) gasLimit = this.DEFAULT_GAS;
151 const web3 = this.helper.getWeb3();
152 const gasPrice = await web3.eth.getGasPrice();
153 // TODO: check execution status
154 await this.helper.executeExtrinsic(
155 signer,
156 'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],
157 true, `Unable to perform evm.call`
158 );
159 }
84160
85 async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {161 async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
86 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);162 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
93 return {collectionId, collectionAddress};169 return {collectionId, collectionAddress};
94 }170 }
171
172 async deployCollectorContract(signer: string): Promise<Contract> {
173 return await this.helper.ethContract.deployByCode(signer, 'Collector', `
174 // SPDX-License-Identifier: UNLICENSED
175 pragma solidity ^0.8.6;
176
177 contract Collector {
178 uint256 collected;
179 fallback() external payable {
180 giveMoney();
181 }
182 function giveMoney() public payable {
183 collected += msg.value;
184 }
185 function getCollected() public view returns (uint256) {
186 return collected;
187 }
188 function getUnaccounted() public view returns (uint256) {
189 return address(this).balance - collected;
190 }
191
192 function withdraw(address payable target) public {
193 target.transfer(collected);
194 collected = 0;
195 }
196 }
197 `);
198 }
95}199}
96 200
97 201
134 eth: EthGroup;238 eth: EthGroup;
135 ethAddress: EthAddressGroup;239 ethAddress: EthAddressGroup;
136 ethNativeContract: NativeContractGroup;240 ethNativeContract: NativeContractGroup;
241 ethContract: ContractGroup;
137242
138 constructor(logger: { log: (msg: any, level: any) => void, level: any }) {243 constructor(logger: { log: (msg: any, level: any) => void, level: any }) {
139 super(logger);244 super(logger);
140 this.eth = new EthGroup(this);245 this.eth = new EthGroup(this);
141 this.ethAddress = new EthAddressGroup(this);246 this.ethAddress = new EthAddressGroup(this);
142 this.ethNativeContract = new NativeContractGroup(this);247 this.ethNativeContract = new NativeContractGroup(this);
248 this.ethContract = new ContractGroup(this);
143 }249 }
144250
145 getWeb3(): Web3 {251 getWeb3(): Web3 {
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
388 type: this.chainLogType.EXTRINSIC,388 type: this.chainLogType.EXTRINSIC,
389 status: result.status,389 status: result.status,
390 call: extrinsic,390 call: extrinsic,
391 signer: this.getSignerAddress(sender),
391 params,392 params,
392 } as IUniqueHelperLog;393 } as IUniqueHelperLog;
393394