Skip to content

Commit

Permalink
p-657 Upgrade web3.js version (#2627)
Browse files Browse the repository at this point in the history
* upgrade test

* fix path

* add log

* use stringToHex

* test numberToHex

* try numberToHex

* remove toHex

* remove log

* add type assertion

* fix nonce?

* merge dev

* add nonce

* add gasPrice

* add gas

* add precompile tx gas

* add precompile gasprice

* debug staking contract

* import issue?

* update deps version

* change gas to str

* Increase the number of transfers

* increase one more :p

* change to ethers

* refactor executeTransaction

* remove unused import

* fix comments
  • Loading branch information
0xverin committed Apr 3, 2024
1 parent 8e55d19 commit b57012b
Show file tree
Hide file tree
Showing 7 changed files with 363 additions and 1,928 deletions.
12 changes: 6 additions & 6 deletions ts-tests/common/setup/setup-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,12 +118,12 @@ async function setupCrossChainTransfer(
const depositNonce = await pConfig.api.query.chainBridge.votes.entries(sourceChainID);

const destResourceId = pConfig.api.consts.bridgeTransfer.nativeTokenResourceId.toHex();
await eConfig.erc20.mint(eConfig.wallets.alice.address, toWei('100000'));
await eConfig.erc20.mint(eConfig.wallets.bob.address, toWei('100000'));
await eConfig.erc20.mint(eConfig.wallets.charlie.address, toWei('100000'));
await eConfig.erc20.mint(eConfig.wallets.dave.address, toWei('100000'));
await eConfig.erc20.mint(eConfig.wallets.eve.address, toWei('100000'));
await eConfig.erc20.mint(eConfig.erc20Handler.address, toWei('300'));
await eConfig.erc20.mint(eConfig.wallets.alice.address, toWei('100000', 'ether'));
await eConfig.erc20.mint(eConfig.wallets.bob.address, toWei('100000', 'ether'));
await eConfig.erc20.mint(eConfig.wallets.charlie.address, toWei('100000', 'ether'));
await eConfig.erc20.mint(eConfig.wallets.dave.address, toWei('100000', 'ether'));
await eConfig.erc20.mint(eConfig.wallets.eve.address, toWei('100000', 'ether'));
await eConfig.erc20.mint(eConfig.erc20Handler.address, toWei('300', 'ether'));
await eConfig.bridge.adminSetResource(eConfig.erc20Handler.address, destResourceId, eConfig.erc20.address);
await eConfig.bridge.adminSetDecimals(eConfig.erc20Handler.address, eConfig.erc20.address, 18, 12, opts);
// votes.entries equivalent to nonce
Expand Down
17 changes: 10 additions & 7 deletions ts-tests/integration-tests/bridge.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { createERCDepositData, describeCrossChainTransfer } from '../common/setup/setup-bridge';
import { step } from 'mocha-steps';
import { toHex } from 'web3-utils';
import { numberToHex } from 'web3-utils';
import { signAndSend, sleep } from '../common/utils';
import { assert } from 'chai';
import { BigNumber, ethers } from 'ethers';

const BN = require('bn.js');
import { BN } from 'bn.js';
const bn100e12 = new BN(10).pow(new BN(12)).mul(new BN(100));

describeCrossChainTransfer('Test Cross-chain Transfer', ``, (context) => {
Expand All @@ -16,7 +15,7 @@ describeCrossChainTransfer('Test Cross-chain Transfer', ``, (context) => {
// const destResourceId = "0x00000000000000000000000000000063a7e2be78898ba83824b0c0cc8dfb6001"
const destResourceId = context.parachainConfig.api.consts.bridgeTransfer.nativeTokenResourceId.toHex();

const depositAmount = toHex(BigNumber.from('100,000,000,000,000,000,000'.replace(/,/g, '')).toString());
const depositAmount = numberToHex('100,000,000,000,000,000,000'.replace(/,/g, ''));
let destinationChainID = parseInt(context.parachainConfig.api.consts.chainBridge.bridgeChainId.toString());
console.log(destinationChainID);

Expand Down Expand Up @@ -122,6 +121,9 @@ describeCrossChainTransfer('Test Cross-chain Transfer', ``, (context) => {

step('Boundary testing on parachain', async function () {
let bridge = context.ethConfig.bridge.connect(context.ethConfig.wallets.bob);

// get context.ethConfig.wallets.bob balance
const balance = await context.ethConfig.erc20.balanceOf(context.ethConfig.wallets.bob.address);
let erc20 = context.ethConfig.erc20.connect(context.ethConfig.wallets.bob);
// substrate native token
const destResourceId = context.parachainConfig.api.consts.bridgeTransfer.nativeTokenResourceId.toHex();
Expand All @@ -133,13 +135,14 @@ describeCrossChainTransfer('Test Cross-chain Transfer', ``, (context) => {
context.ethConfig.wallets.bob.address,
maximum_issuance.sub(new BN(1000)).mul(new BN(1000000)).toString()
);
const depositAmount = maximum_issuance.sub(total_issuance).add(new BN(1000)).mul(new BN(1000000));
const depositAmount = numberToHex('100,000,000,000,000'.replace(/,/g, ''));
let destinationChainID = parseInt(context.parachainConfig.api.consts.chainBridge.bridgeChainId.toString());

const destinationRecipientAddress = '0x1cbd2d43530a44705ad088af313e18f80b53ef16b36177cd4b77b846f2a5f07c';
await erc20.approve(context.ethConfig.erc20Handler.address, `0x${depositAmount.toString('hex')}`);
await erc20.approve(context.ethConfig.erc20Handler.address, depositAmount);
await sleep(2);
let data = createERCDepositData(`0x${depositAmount.toString('hex')}`, 32, destinationRecipientAddress);
let data = createERCDepositData(depositAmount, 32, destinationRecipientAddress);

await bridge.deposit(destinationChainID, destResourceId, data);
let expectResult = false;
const block = await context.parachainConfig.api.rpc.chain.getBlock();
Expand Down
13 changes: 8 additions & 5 deletions ts-tests/integration-tests/evm-contract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { step } from 'mocha-steps';

import { signAndSend, describeLitentry, loadConfig, sleep, sudoWrapperTC } from '../common/utils';
import { evmToAddress } from '@polkadot/util-crypto';
import Web3 from 'web3';
import { Web3 } from 'web3';

import { compiled } from '../common/utils/compile';

Expand Down Expand Up @@ -102,7 +102,6 @@ describeLitentry('Test EVM Module Contract', ``, (context) => {
// Create deploy function
const deploy = async (accountFrom: any) => {
console.log(`Attempting to deploy from account ${accountFrom.address}`);

// Create contract instance
const hello = new web3.eth.Contract(abi);

Expand All @@ -117,6 +116,8 @@ describeLitentry('Test EVM Module Contract', ``, (context) => {
{
data: helloTx.encodeABI(),
gas: await helloTx.estimateGas(),
gasPrice: await web3.eth.getGasPrice(),
nonce: await web3.eth.getTransactionCount(accountFrom.address),
},
accountFrom.privateKey
);
Expand All @@ -134,13 +135,13 @@ describeLitentry('Test EVM Module Contract', ``, (context) => {
}

// Test get message contract method
const sayMessage = async (contractAddress: string) => {
const sayMessage = async (contractAddress: string): Promise<string> => {
// 4. Create contract instance
const hello = new web3.eth.Contract(abi, contractAddress);
console.log(`Making a call to contract at address: ${contractAddress}`);

// 6. Call contract
const data = await hello.methods.sayMessage().call();
const data: string = await hello.methods.sayMessage().call();

console.log(`The current message is: ${data}`);

Expand All @@ -166,6 +167,8 @@ describeLitentry('Test EVM Module Contract', ``, (context) => {
to: contractAddress,
data: helloTx.encodeABI(),
gas: await helloTx.estimateGas(),
nonce: await web3.eth.getTransactionCount(accountFrom.address),
gasPrice: await web3.eth.getGasPrice(),
},
accountFrom.privateKey
);
Expand All @@ -175,7 +178,7 @@ describeLitentry('Test EVM Module Contract', ``, (context) => {
console.log(`Tx successful with hash: ${createReceipt.transactionHash}`);
};
const setMsg = await setMessage(deployed.contractAddress!, evmAccountRaw, 'Goodbye World');
const sayMsg = await sayMessage(deployed.contractAddress!);
const sayMsg = await sayMessage(deployed.contractAddress!)
const setResult = sayMsg === 'Goodbye World' ? 1 : 0;
assert.equal(1, setResult, 'Contract modified storage query mismatch');

Expand Down
2 changes: 1 addition & 1 deletion ts-tests/integration-tests/evm-transfer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { signAndSend, describeLitentry, loadConfig, sudoWrapperTC } from '../com
import { hexToU8a, u8aToHex } from '@polkadot/util';
import { createPair, encodeAddress } from '@polkadot/keyring';
import { evmToAddress } from '@polkadot/util-crypto';
import Web3 from 'web3';
import { Web3 } from 'web3';

describeLitentry('Test EVM Module Transfer', ``, (context) => {
console.log(`Test EVM Module Transfer`);
Expand Down
141 changes: 71 additions & 70 deletions ts-tests/integration-tests/precompile-contract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,13 @@ import {
sudoWrapperGC,
sudoWrapperTC,
} from '../common/utils';
import Web3 from 'web3';
import precompileStakingContractAbi from '../common/abi/precompile/Staking.json';
import precompileBridgeContractAbi from '../common/abi/precompile/Bridge.json';
const BN = require('bn.js');
import { mnemonicGenerate, mnemonicToMiniSecret, evmToAddress } from '@polkadot/util-crypto';
import { evmToAddress } from '@polkadot/util-crypto';
import { KeyringPair } from '@polkadot/keyring/types';
import { HexString } from '@polkadot/util/types';

import { ethers } from 'ethers';
const toBigNumber = (int: number) => int * 1e12;
const bn1e12 = new BN(10).pow(new BN(12)).mul(new BN(1));

Expand All @@ -36,34 +35,33 @@ describeLitentry('Test Parachain Precompile Contract', ``, (context) => {
// transform to bytes32(public key) reference:https://polkadot.subscan.io/tools/format_transform?input=5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY&type=All
const collatorPublicKey = '0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d';

const web3 = new Web3(config.parachain_ws);
// const web3 = new Web3(config.parachain_ws);

const provider = new ethers.providers.WebSocketProvider(config.parachain_ws);
const wallet = new ethers.Wallet(evmAccountRaw.privateKey, provider);

const precompileStakingContract = new web3.eth.Contract(
precompileStakingContractAbi as AbiItem[],
precompileStakingContractAddress
const precompileStakingContract = new ethers.Contract(
precompileStakingContractAddress,
precompileStakingContractAbi,
provider
);
const precompileBridgeContract = new web3.eth.Contract(
precompileBridgeContractAbi as AbiItem[],
precompileBridgeContractAddress
const precompileBridgeContract = new ethers.Contract(
precompileBridgeContractAddress,
precompileBridgeContractAbi,
provider
);

const executeTransaction = async (delegateTransaction: any, contractAddress: HexString, label = '') => {
console.log(`=== Executing ${label} ===`);

// estimate gas doesn't work
// const gas = await delegateTransaction.estimateGas();
// console.log("gas", gas);

const transaction = await web3.eth.accounts.signTransaction(
{
to: contractAddress,
data: delegateTransaction.encodeABI(),
gas: 1000000,
},
evmAccountRaw.privateKey
);

return await web3.eth.sendSignedTransaction(transaction.rawTransaction!);
const tx = await wallet.sendTransaction({
to: contractAddress,
data: delegateTransaction,
gasLimit: 1000000,
nonce: await wallet.getTransactionCount(),
gasPrice: await provider.getGasPrice(),
});
await tx.wait();
return tx;
};

const printBalance = (label: string, bl: any) => {
Expand Down Expand Up @@ -105,9 +103,7 @@ describeLitentry('Test Parachain Precompile Contract', ``, (context) => {
};

const isPendingRequest = async () =>
await precompileStakingContract.methods
.delegationRequestIsPending(evmAccountRaw.publicKey, collatorPublicKey)
.call();
await precompileStakingContract.delegationRequestIsPending(evmAccountRaw.publicKey, collatorPublicKey);

const collatorDetails = async () => {
const response = await context.api.query.parachainStaking.autoCompoundingDelegations(collatorPublicKey);
Expand All @@ -116,25 +112,22 @@ describeLitentry('Test Parachain Precompile Contract', ``, (context) => {
};

step('Address with not sufficient amount of tokens', async function () {
// Create valid Substrate-compatible seed from mnemonic
const randomSeed = mnemonicToMiniSecret(mnemonicGenerate());
const secretKey = Buffer.from(randomSeed).toString('hex');

const delegateWithAutoCompound = precompileStakingContract.methods.delegateWithAutoCompound(
collatorPublicKey,
toBigNumber(60),
1
const randomEvmWallet = ethers.Wallet.createRandom();
const delegateWithAutoCompound = precompileStakingContract.interface.encodeFunctionData(
'delegateWithAutoCompound',
[collatorPublicKey, toBigNumber(60), 1]
);

try {
await web3.eth.accounts.signTransaction(
{
to: precompileStakingContractAddress,
data: delegateWithAutoCompound.encodeABI(),
gas: await delegateWithAutoCompound.estimateGas(),
},
secretKey
);
const tx = await randomEvmWallet.sendTransaction({
to: precompileStakingContractAddress,
data: delegateWithAutoCompound,
gasLimit: 1000000,
nonce: await randomEvmWallet.getTransactionCount(),
gasPrice: await provider.getGasPrice(),
});
await tx.wait();

expect(true).to.eq(false); // test should fail here
} catch (e) {
expect(e).to.be.instanceof(Error);
Expand Down Expand Up @@ -170,10 +163,9 @@ describeLitentry('Test Parachain Precompile Contract', ``, (context) => {
const autoCompoundPercent = 20;

// delegateWithAutoCompound(collator, amount, percent)
const delegateWithAutoCompound = precompileStakingContract.methods.delegateWithAutoCompound(
collatorPublicKey,
toBigNumber(60),
autoCompoundPercent
const delegateWithAutoCompound = precompileStakingContract.interface.encodeFunctionData(
'delegateWithAutoCompound',
[collatorPublicKey, toBigNumber(60), autoCompoundPercent]
);

let afterDelegateBalance = balance;
Expand All @@ -196,10 +188,10 @@ describeLitentry('Test Parachain Precompile Contract', ``, (context) => {
}

// delegatorBondMore(collator, amount)
const delegatorBondMore = precompileStakingContract.methods.delegatorBondMore(
const delegatorBondMore = precompileStakingContract.interface.encodeFunctionData('delegatorBondMore', [
collatorPublicKey,
toBigNumber(1)
);
toBigNumber(1),
]);
await executeTransaction(delegatorBondMore, precompileStakingContractAddress, 'delegatorBondMore');

const { data: balanceAfterBondMore } = await context.api.query.system.account(evmAccountRaw.mappedAddress);
Expand All @@ -211,20 +203,21 @@ describeLitentry('Test Parachain Precompile Contract', ``, (context) => {
afterDelegateBalance.reserved.toNumber() + toBigNumber(1)
);

// setAutoCompound(collator, percent);
const setAutoCompound = precompileStakingContract.methods.setAutoCompound(
const setAutoCompound = precompileStakingContract.interface.encodeFunctionData('setAutoCompound', [
collatorPublicKey,
autoCompoundPercent + 5
);
autoCompoundPercent + 5,
]);

await executeTransaction(setAutoCompound, precompileStakingContractAddress, 'setAutoCompound');
const collatorAfterCompound = await collatorDetails();
expect(collatorAfterCompound.value).to.eq(autoCompoundPercent + 5);

// scheduleDelegatorBondLess(collator, amount)
expect(await isPendingRequest()).to.be.false;
const scheduleDelegatorBondLess = precompileStakingContract.methods.scheduleDelegatorBondLess(
collatorPublicKey,
toBigNumber(5)

const scheduleDelegatorBondLess = precompileStakingContract.interface.encodeFunctionData(
'scheduleDelegatorBondLess',
[collatorPublicKey, toBigNumber(5)]
);
await executeTransaction(
scheduleDelegatorBondLess,
Expand All @@ -234,7 +227,11 @@ describeLitentry('Test Parachain Precompile Contract', ``, (context) => {
expect(await isPendingRequest()).to.be.true;

// cancelDelegationRequest(collator)
const cancelDelegationRequest = precompileStakingContract.methods.cancelDelegationRequest(collatorPublicKey);
const cancelDelegationRequest = precompileStakingContract.interface.encodeFunctionData(
'cancelDelegationRequest',
[collatorPublicKey]
);

expect(await isPendingRequest()).to.be.true;
await executeTransaction(cancelDelegationRequest, precompileStakingContractAddress, 'cancelDelegationRequest');
expect(await isPendingRequest()).to.be.false;
Expand All @@ -252,9 +249,9 @@ describeLitentry('Test Parachain Precompile Contract', ``, (context) => {
await context.api.rpc.chain.getBlock();

// executeDelegationRequest(delegator, collator);
const executeDelegationRequest = precompileStakingContract.methods.executeDelegationRequest(
evmAccountRaw.publicKey,
collatorPublicKey
const executeDelegationRequest = precompileStakingContract.interface.encodeFunctionData(
'executeDelegationRequest',
[evmAccountRaw.publicKey, collatorPublicKey]
);
await executeTransaction(
executeDelegationRequest,
Expand All @@ -272,7 +269,10 @@ describeLitentry('Test Parachain Precompile Contract', ``, (context) => {

// testing revoke delegation + execute
// scheduleRevokeDelegation(collator);
const scheduleRevokeDelegation = precompileStakingContract.methods.scheduleRevokeDelegation(collatorPublicKey);
const scheduleRevokeDelegation = precompileStakingContract.interface.encodeFunctionData(
'scheduleRevokeDelegation',
[collatorPublicKey]
);
await executeTransaction(
scheduleRevokeDelegation,
precompileStakingContractAddress,
Expand All @@ -293,7 +293,10 @@ describeLitentry('Test Parachain Precompile Contract', ``, (context) => {
expect(balanceAfterRevoke.reserved.toNumber()).to.eq(0);

// delegate(collator, amount);
const delegate = precompileStakingContract.methods.delegate(collatorPublicKey, toBigNumber(57));
const delegate = precompileStakingContract.interface.encodeFunctionData('delegate', [
collatorPublicKey,
toBigNumber(57),
]);
await executeTransaction(delegate, precompileStakingContractAddress, 'delegate');
const { data: balanceAfterDelegate } = await context.api.query.system.account(evmAccountRaw.mappedAddress);
expect(balanceAfterDelegate.reserved.toNumber()).to.eq(toBigNumber(57));
Expand Down Expand Up @@ -326,15 +329,13 @@ describeLitentry('Test Parachain Precompile Contract', ``, (context) => {

// The above two steps are necessary, otherwise the contract transaction will be reverted.
// transfer native token
const transferNativeTx = precompileBridgeContract.methods.transferNative(
const transferNativeTx = precompileBridgeContract.interface.encodeFunctionData('transferNative', [
bn1e12 / 100, // 0.01 LIT
dest_address,
0
);

const res = await executeTransaction(transferNativeTx, precompileBridgeContractAddress, 'transferNative');
expect(res.status).to.eq(true);
0,
]);

await executeTransaction(transferNativeTx, precompileBridgeContractAddress, 'transferNative');
const eventsPromise = subscribeToEvents('chainBridge', 'FungibleTransfer', context.api);
const events = (await eventsPromise).map(({ event }) => event);

Expand Down

0 comments on commit b57012b

Please sign in to comment.