git.delta.rocks / unique-network / refs/commits / 470ffd5ce9b5

difftreelog

source

js-packages/tests/eth/migration.seqtest.ts9.7 KiBsourcehistory
1// 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 {expect, itEth, usingEthPlaygrounds} from '@unique/test-utils/eth/util.js';18import type {IKeyringPair} from '@polkadot/types/types';19import {Struct} from '@polkadot/types';2021import type {IEvent} from '@unique-nft/playgrounds/types.js';22import type {InterfaceTypes} from '@polkadot/types/types/registry';23import {ApiPromise} from '@polkadot/api';2425const encodeEvent = (api: ApiPromise, pallet: string, palletEvents: string, event: string, fields: any) => {26  const palletIndex = api.runtimeMetadata.asV14.pallets.find(p => p.name.toString() == pallet)!.index.toNumber();27  const eventMeta = api.events[palletEvents][event].meta;28  const eventIndex = eventMeta.index.toNumber();29  const data = [30    palletIndex, eventIndex,31  ];32  const metaEvent = api.registry.findMetaEvent(new Uint8Array(data));33  data.push(...new Struct(api.registry, {data: metaEvent}, {data: fields}).toU8a());3435  const typeName = api.registry.lookup.names.find(n => n.endsWith('RuntimeEvent'))!;36  const obj = api.registry.createType(typeName, new Uint8Array(data)) as InterfaceTypes['RuntimeEvent'];37  return obj.toHex();38};3940describe('EVM Migrations', () => {41  let superuser: IKeyringPair;42  let charlie: IKeyringPair;4344  before(async function() {45    await usingEthPlaygrounds(async (_helper, privateKey) => {46      superuser = await privateKey('//Alice');47      charlie = await privateKey('//Charlie');48    });49  });5051  // todo:playgrounds requires sudo, look into later52  itEth('Deploy contract saved state', async ({helper}) => {53    /*54      contract StatefulContract {55        uint counter;56        mapping (uint => uint) kv;5758        function inc() public {59          counter = counter + 1;60        }61        function counterValue() public view returns (uint) {62          return counter;63        }6465        function set(uint key, uint value) public {66          kv[key] = value;67        }6869        function get(uint key) public view returns (uint) {70          return kv[key];71        }72      }73    */74    const ADDRESS = '0x4956bf52ef9ed8789f21bc600e915e0d961079f6';75    const CODE = '0x608060405234801561001057600080fd5b506004361061004c5760003560e01c80631ab06ee514610051578063371303c01461006d5780637bfdec3b146100775780639507d39a14610095575b600080fd5b61006b60048036038101906100669190610160565b6100c5565b005b6100756100e1565b005b61007f6100f8565b60405161008c91906101af565b60405180910390f35b6100af60048036038101906100aa9190610133565b610101565b6040516100bc91906101af565b60405180910390f35b8060016000848152602001908152602001600020819055505050565b60016000546100f091906101ca565b600081905550565b60008054905090565b600060016000838152602001908152602001600020549050919050565b60008135905061012d8161025e565b92915050565b60006020828403121561014957610148610259565b5b60006101578482850161011e565b91505092915050565b6000806040838503121561017757610176610259565b5b60006101858582860161011e565b92505060206101968582860161011e565b9150509250929050565b6101a981610220565b82525050565b60006020820190506101c460008301846101a0565b92915050565b60006101d582610220565b91506101e083610220565b9250827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff038211156102155761021461022a565b5b828201905092915050565b6000819050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b600080fd5b61026781610220565b811461027257600080fd5b5056fea26469706673582212206a02d2fb5c244105ab884961479c1aee3b4c1011e4b5530ab483eb22344a865664736f6c63430008060033';76    const DATA = [77      // counter = 1078      ['0x0000000000000000000000000000000000000000000000000000000000000000', '0x000000000000000000000000000000000000000000000000000000000000000a'],79      // kv = {1: 1, 2: 2, 3: 3, 4: 4},80      ['0xcc69885fda6bcc1a4ace058b4a62bf5e179ea78fd58a1ccd71c22cc9b688792f', '0x0000000000000000000000000000000000000000000000000000000000000001'],81      ['0xd9d16d34ffb15ba3a3d852f0d403e2ce1d691fb54de27ac87cd2f993f3ec330f', '0x0000000000000000000000000000000000000000000000000000000000000002'],82      ['0x7dfe757ecd65cbd7922a9c0161e935dd7fdbcc0e999689c7d31633896b1fc60b', '0x0000000000000000000000000000000000000000000000000000000000000003'],83      ['0xedc95719e9a3b28dd8e80877cb5880a9be7de1a13fc8b05e7999683b6b567643', '0x0000000000000000000000000000000000000000000000000000000000000004'],84    ];8586    const caller = await helper.eth.createAccountWithBalance(superuser);8788    const txBegin = helper.constructApiCall('api.tx.evmMigration.begin', [ADDRESS]);89    const txSetData = helper.constructApiCall('api.tx.evmMigration.setData', [ADDRESS, DATA]);90    const txFinish = helper.constructApiCall('api.tx.evmMigration.finish', [ADDRESS, CODE]);91    await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [txBegin])).to.be.fulfilled;92    await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [txSetData])).to.be.fulfilled;93    await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [txFinish])).to.be.fulfilled;9495    const web3 = helper.getWeb3();96    const contract = new web3.eth.Contract([97      {98        inputs: [],99        name: 'counterValue',100        outputs: [{101          internalType: 'uint256',102          name: '',103          type: 'uint256',104        }],105        stateMutability: 'view',106        type: 'function',107      },108      {109        inputs: [{110          internalType: 'uint256',111          name: 'key',112          type: 'uint256',113        }],114        name: 'get',115        outputs: [{116          internalType: 'uint256',117          name: '',118          type: 'uint256',119        }],120        stateMutability: 'view',121        type: 'function',122      },123    ], ADDRESS, {from: caller, gas: helper.eth.DEFAULT_GAS});124125    expect(await contract.methods.counterValue().call()).to.be.equal('10');126    for(let i = 1; i <= 4; i++) {127      expect(await contract.methods.get(i).call()).to.be.equal(i.toString());128    }129  });130  itEth('Fake collection creation on substrate side', async ({helper}) => {131    const txInsertEvents = helper.constructApiCall('api.tx.evmMigration.insertEvents', [[132      encodeEvent(helper.getApi(), 'Common', 'common', 'CollectionCreated', [133        // Collection Id134        9999,135        // Collection mode: NFT136        1,137        // Owner138        charlie.address,139      ]),140    ]]);141    await helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [txInsertEvents]);142    const event = helper.chainLog[helper.chainLog.length - 1].events as IEvent[];143    const eventStrings = event.map(e => `${e.section}.${e.method}`);144145    expect(eventStrings).to.contain('common.CollectionCreated');146  });147  itEth('Fake token creation on substrate side', async ({helper}) => {148    const txInsertEvents = helper.constructApiCall('api.tx.evmMigration.insertEvents', [[149      encodeEvent(helper.getApi(), 'Common', 'common', 'ItemCreated', [150        // Collection Id151        9999,152        // TokenId153        9999,154        // Owner155        {Substrate: charlie.address},156        // Amount157        1,158      ]),159    ]]);160    await helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [txInsertEvents]);161    const event = helper.chainLog[helper.chainLog.length - 1].events as IEvent[];162    const eventStrings = event.map(e => `${e.section}.${e.method}`);163164    expect(eventStrings).to.contain('common.ItemCreated');165  });166  itEth('Fake token creation on ethereum side', async ({helper}) => {167    const collection = await helper.nft.mintCollection(superuser);168    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);169    const caller = await helper.eth.createAccountWithBalance(superuser);170    const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', caller);171172    const events: any = [];173    contract.events.allEvents((_: any, event: any) => {174      events.push(event);175    });176177    {178      const txInsertEthLogs = helper.constructApiCall('api.tx.evmMigration.insertEthLogs', [[179        {180        // Contract, which has emitted this log181          address: collectionAddress,182183          topics: [184            // First topic - event signature185            helper.getWeb3().eth.abi.encodeEventSignature('Transfer(address,address,uint256)'),186            // Rest of topics - indexed event fields in definition order187            helper.getWeb3().eth.abi.encodeParameter('address', '0x' + '00'.repeat(20)),188            helper.getWeb3().eth.abi.encodeParameter('address', caller),189            helper.getWeb3().eth.abi.encodeParameter('uint256', 9999),190          ],191192          // Every field coming from event, which is not marked as indexed, should be encoded here193          // NFT transfer has no such fields, but here is an example for some other possible event:194          // data: helper.getWeb3().eth.abi.encodeParameters(['uint256', 'address'], [22, collectionAddress])195          data: [],196        },197      ]]);198      await helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [txInsertEthLogs]);199    }200201    if(events.length == 0) await helper.wait.newBlocks(1);202    const event = events[0];203204    expect(event.address).to.be.equal(collectionAddress);205    expect(event.returnValues.from).to.be.equal('0x' + '00'.repeat(20));206    expect(event.returnValues.to).to.be.equal(caller);207    expect(event.returnValues.tokenId).to.be.equal('9999');208  });209});