difftreelog
Fix transfer.nload script
in: master
1 file changed
tests/src/transfer.nload.tsdiffbeforeafterboth14// You should have received a copy of the GNU General Public License14// You should have received a copy of the GNU General Public License15// 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/>.161617import {ApiPromise} from '@polkadot/api';17import os from 'os';18import {IKeyringPair} from '@polkadot/types/types';18import {IKeyringPair} from '@polkadot/types/types';19import usingApi, {submitTransactionAsync} from './substrate/substrate-api';19import {usingPlaygrounds} from './util';20import waitNewBlocks from './substrate/wait-new-blocks';20import {UniqueHelper} from './util/playgrounds/unique';21import * as cluster from 'cluster';21import * as notReallyCluster from 'cluster'; // https://github.com/nodejs/node/issues/42271#issuecomment-106341534622import os from 'os';22const cluster = notReallyCluster as unknown as notReallyCluster.Cluster;232324async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {24async function findUnusedAddress(helper: UniqueHelper, privateKey: (account: string) => Promise<IKeyringPair>, seedAddition = ''): Promise<IKeyringPair> {25 let bal = 0n;25 let bal = 0n;26 let unused;26 let unused;27 do {27 do {28 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;28 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;29 unused = privateKeyWrapper(`//${randomSeed}`);29 unused = await privateKey(`//${randomSeed}`);30 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();30 bal = await helper.balance.getSubstrate(unused.address);31 } while (bal !== 0n);31 } while (bal !== 0n);32 return unused;32 return unused;33}33}343435function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {35function findUnusedAddresses(helper: UniqueHelper, privateKey: (account: string) => Promise<IKeyringPair>, amount: number): Promise<IKeyringPair[]> {36 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));36 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(helper, privateKey, '_' + Date.now())));37}37}383839// Innacurate transfer fee39// Innacurate transfer fee54 counters = {};54 counters = {};55}55}565657async function distributeBalance(source: IKeyringPair, api: ApiPromise, totalAmount: bigint, stages: number) {57async function distributeBalance(source: IKeyringPair, helper: UniqueHelper, privateKey: (account: string) => Promise<IKeyringPair>, totalAmount: bigint, stages: number) {58 const accounts = [source];58 const accounts = [source];59 // we don't need source in output array59 // we don't need source in output array60 const failedAccounts = [0];60 const failedAccounts = [0];616162 const finalUserAmount = 2 ** stages - 1;62 const finalUserAmount = 2 ** stages - 1;63 accounts.push(...await findUnusedAddresses(api, finalUserAmount));63 accounts.push(...await findUnusedAddresses(helper, privateKey, finalUserAmount));64 // findUnusedAddresses produces at least 1 request per user64 // findUnusedAddresses produces at least 1 request per user65 increaseCounter('requests', finalUserAmount);65 increaseCounter('requests', finalUserAmount);666667 for (let stage = 0; stage < stages; stage++) {67 for (let stage = 0; stage < stages; stage++) {68 const usersWithBalance = 2 ** stage;68 const usersWithBalance = 2 ** stage;69 const amount = totalAmount / (2n ** BigInt(stage)) - FEE * BigInt(stage);69 const amount = totalAmount / (2n ** BigInt(stage)) - FEE * BigInt(stage);70 // console.log(`Stage ${stage}/${stages}, ${usersWithBalance} => ${usersWithBalance * 2} = ${amount}`);70 // console.log(`Stage ${stage}/${stages}, ${usersWithBalance} => ${usersWithBalance * 2} = ${amount}`);71 const txs = [];71 const txs: Promise<boolean | void>[] = [];72 for (let i = 0; i < usersWithBalance; i++) {72 for (let i = 0; i < usersWithBalance; i++) {73 const newUser = accounts[i + usersWithBalance];73 const newUser = accounts[i + usersWithBalance];74 // console.log(`${accounts[i].address} => ${newUser.address} = ${amountToSplit}`);74 // console.log(`${accounts[i].address} => ${newUser.address} = ${amountToSplit}`);75 const tx = api.tx.balances.transfer(newUser.address, amount);75 const tx = helper.balance.transferToSubstrate(accounts[i], newUser.address, amount);76 txs.push(submitTransactionAsync(accounts[i], tx).catch(() => {76 txs.push(tx.catch(() => {77 failedAccounts.push(i + usersWithBalance);77 failedAccounts.push(i + usersWithBalance);78 increaseCounter('txFailed', 1);78 increaseCounter('txFailed', 1);79 }));79 }));909091if (cluster.isMaster) {91if (cluster.isMaster) {92 let testDone = false;92 let testDone = false;93 usingApi(async (api) => {93 usingPlaygrounds(async (helper) => {94 const prevCounters: { [key: string]: number } = {};94 const prevCounters: { [key: string]: number } = {};95 while (!testDone) {95 while (!testDone) {96 for (const name in counters) {96 for (const name in counters) {103 console.log(`${name.padEnd(15)} = ${counters[name] - prevCounters[name]}`);103 console.log(`${name.padEnd(15)} = ${counters[name] - prevCounters[name]}`);104 prevCounters[name] = counters[name];104 prevCounters[name] = counters[name];105 }105 }106 await waitNewBlocks(api, 1);106 await helper.wait.newBlocks(1);107 }107 }108 });108 });109 const waiting: Promise<void>[] = [];109 const waiting: Promise<void>[] = [];110 console.log(`Starting ${os.cpus().length} workers`);110 console.log(`Starting ${os.cpus().length} workers`);111 usingApi(async (api, privateKeyWrapper) => {111 usingPlaygrounds(async (helper, privateKey) => {112 const alice = privateKeyWrapper('//Alice');112 const alice = await privateKey('//Alice');113 for (const id in os.cpus()) {113 for (const id in os.cpus()) {114 const WORKER_NAME = `//LoadWorker${id}_${Date.now()}`;114 const WORKER_NAME = `//LoadWorker${id}_${Date.now()}`;115 const workerAccount = privateKeyWrapper(WORKER_NAME);115 const workerAccount = await privateKey(WORKER_NAME);116 const tx = api.tx.balances.transfer(workerAccount.address, 400n * 10n ** 23n);116 await helper.balance.transferToSubstrate(alice, workerAccount.address, 400n * 10n ** 23n);117 await submitTransactionAsync(alice, tx);118117119 const worker = cluster.fork({118 const worker = cluster.fork({120 WORKER_NAME,119 WORKER_NAME,132 });131 });133} else {132} else {134 increaseCounter('startedWorkers', 1);133 increaseCounter('startedWorkers', 1);135 usingApi(async (api, privateKeyWrapper) => {134 usingPlaygrounds(async (helper, privateKey) => {136 await distributeBalance(privateKeyWrapper(process.env.WORKER_NAME as string), api, 400n * 10n ** 22n, 10);135 await distributeBalance(await privateKey(process.env.WORKER_NAME as string), helper, privateKey, 400n * 10n ** 22n, 10);137 });136 });138 const interval = setInterval(() => {137 const interval = setInterval(() => {139 flushCounterToMaster();138 flushCounterToMaster();