12import * as fs from 'fs';3import {usingPlaygrounds} from '../../util';4import path, {dirname} from 'path';5import {isInteger, parse} from 'lossless-json';6import {fileURLToPath} from 'url';789const WS_ENDPOINT = 'ws://localhost:9944';10const DONOR_SEED = '//Alice';11const UPDATE_IF_VERSION = 942057;1213export function customNumberParser(value: any) {14 return isInteger(value) ? BigInt(value) : parseFloat(value);15}1617export const migrateLockedToFreeze = async(options: { wsEndpoint: string; donorSeed: string } = {18 wsEndpoint: WS_ENDPOINT,19 donorSeed: DONOR_SEED,20}) => {21 await usingPlaygrounds(async (helper, privateKey) => {22 const api = helper.getApi();23 24 console.log((api.consts.system.version as any).specVersion.toNumber());25 if((api.consts.system.version as any).specVersion.toNumber() != UPDATE_IF_VERSION) {26 console.log("Version isn't 942057.");27 return;28 }2930 31 const signer = await privateKey(options.donorSeed);32 console.log('2. Getting sudo:', signer.address);3334 35 console.log('3. Parsing chainql results...');36 const dirName = dirname(fileURLToPath(import.meta.url));37 const parsingResult = parse(fs.readFileSync(path.resolve(dirName, 'output.json'), 'utf-8'), undefined, customNumberParser);3839 const chainqlImportData = parsingResult as {40 address: string;41 balance: string;42 account: {43 fee_frozen: string,44 free: string,45 misc_frozen: string,46 reserved: string,47 },48 locks: {49 amount: string,50 id: string,51 }[],52 stakes: object,53 unstakes: object,54 }[];55 testChainqlData(chainqlImportData);5657 const stakers = chainqlImportData.map((i) => i.address);5859 60 console.log('3.1 Splitting into chunks...');61 const stakersChunks = chunk(stakers, 100);62 console.log('3.1 Done, total chunks:', stakersChunks.length);6364 65 console.log('4. Getting sudo nonce...');66 const signerAccount = (67 await api.query.system.account(signer.address)68 ).toJSON() as any;6970 let nonce: number = signerAccount.nonce;71 console.log('4. Sudo nonce is:', nonce);7273 74 console.log('5. Signing transactions...');75 const signedTxs = [];76 for(const chunk of stakersChunks) {77 const tx = api.tx.sudo.sudo(api.tx.appPromotion.upgradeAccounts(chunk));78 const signed = tx.sign(signer, {79 blockHash: api.genesisHash,80 genesisHash: api.genesisHash,81 runtimeVersion: api.runtimeVersion,82 nonce: nonce++,83 });84 signedTxs.push(signed);85 }8687 88 console.log('6. Sending transactions...');89 const promises = signedTxs.map((tx) => api.rpc.author.submitAndWatchExtrinsic(tx));90 91 console.log('6.1 Waiting all transactions settled...');92 const res = await Promise.allSettled(promises);9394 console.log('Wait 5 blocks for transactions to be included in a block...');95 await helper.wait.newBlocks(5);96 97 console.log('6.2 Getting failed transactions...');98 const failedTx = res.filter((r) => r.status == 'rejected') as PromiseRejectedResult[];99 console.log('6.2. total failedTxs:', failedTx.length);100101 102 for(const tx of failedTx) {103 console.log(tx.reason);104 }105106 107 console.log('7. Check balances...');108 let blocksLeft = 10;109 let notMigrated = stakers;110 const suspiciousAccounts = [];111 do {112 console.log('blocks left:', blocksLeft);113 const _notMigrated: string[] = [];114 console.log('accounts to migrate...', notMigrated.length);115 for(const accountToMigrate of notMigrated) {116 let accountMigrated = true;117 118 const oldAccount = chainqlImportData.find(acc => acc.address === accountToMigrate);119 if(!oldAccount) {120 console.log('Cannot find old account data for', accountMigrated);121 accountMigrated = false;122 _notMigrated.push(accountToMigrate);123 continue;124 }125126 127 const balance = await api.query.system.account(accountToMigrate) as any;128 129 const free = balance.data.free;130 const reserved = balance.data.reserved;131 const frozen = balance.data.frozen;132 133 const oldFree = oldAccount.account.free;134 const oldReserved = oldAccount.account.reserved;135 const oldFrozen = oldAccount.account.fee_frozen;136 137 if(oldFree.toString() !== free.toString()) {138 console.log('Old free !== New free, which is probably not a problem', oldFree.toString(), free.toString());139 suspiciousAccounts.push(accountToMigrate);140 }141 if(oldFrozen.toString() !== frozen.toString()) {142 console.log('Old frozen !== New frozen, which is probably not a problem', oldFrozen.toString(), frozen.toString());143 suspiciousAccounts.push(accountToMigrate);144 }145 if(oldReserved.toString() !== reserved.toString()) {146 console.log('Old reserved !== New reserved, which is probably not a problem', oldReserved.toString(), reserved.toString());147 suspiciousAccounts.push(accountToMigrate);148 }149150 151 const locks = await helper.balance.getLocked(accountToMigrate);152 const appPromoLocks = locks.filter(lock => lock.id === 'appstake');153 if(appPromoLocks.length !== 0) {154 console.log('Account still has app-promo lock');155 accountMigrated = false;156 }157158 159 let freezes = await api.query.balances.freezes(accountToMigrate) as any;160 freezes = freezes.map((freez: any) => ({id: freez.id.toString(), amount: freez.amount.toString()}));161 if(!freezes) {162 console.log('Account does not have freezes');163 accountMigrated = false;164 } else {165 const oldAppPromoLocks = oldAccount.locks.filter(l => l.id === '0x6170707374616b65'); 166 167 if(freezes.length !== 1) {168 console.log('freezes.length !== 1 and old appPromoLocks.length', freezes.length, oldAppPromoLocks.length);169 accountMigrated = false;170 } else {171 const appPromoFreez = freezes[0];172 173 if(appPromoFreez.amount.toString() !== oldAppPromoLocks[0].amount.toString()) {174 console.log('freezes amount !== old appPromoLocks amount', appPromoFreez.amount.toString(), oldAppPromoLocks[0].amount.toString());175 accountMigrated = false;176 }177 178 if(appPromoFreez.id !== '0x6170707374616b656170707374616b65') {179 console.log('Got freez with incorrect id:', appPromoFreez.id);180 accountMigrated = false;181 }182 }183 }184185 186 const stakesNumber = await helper.staking.getStakesNumber({Substrate: accountToMigrate});187 const oldStakesNumber = oldAccount.stakes ? Object.keys(oldAccount.stakes).length : 0;188 if(stakesNumber.toString() !== oldStakesNumber.toString()) {189 console.log('Old stakes number !== New stakes number', oldStakesNumber, stakesNumber);190 accountMigrated = false;191 }192193 194 const pendingUnstakes = await helper.staking.getPendingUnstake({Substrate: accountToMigrate});195 const totalStaked = await helper.staking.getTotalStaked({Substrate: accountToMigrate});196 const totalBalanceInAppPromo = pendingUnstakes + totalStaked;197 if(totalBalanceInAppPromo.toString() !== oldAccount.balance.toString()) {198 console.log('totalBalanceInAppPromo !== old locked in app promo', totalBalanceInAppPromo.toString(), oldAccount.balance.toString());199 accountMigrated = false;200 }201202 203 if(!accountMigrated) {204 console.log('Add to not migrated:', accountToMigrate);205 _notMigrated.push(accountToMigrate);206 }207 }208209 blocksLeft--;210 notMigrated = _notMigrated;211 await helper.wait.newBlocks(1);212 } while(blocksLeft > 0 && notMigrated.length !== 0);213214 console.log('Not migrated accounts...', notMigrated.length);215 if(suspiciousAccounts.length > 0) {216 console.log('Saving suspicious accounts to suspicious.json:');217 fs.writeFileSync('./suspicious.json', JSON.stringify(suspiciousAccounts));218 }219 if(notMigrated.length > 0) {220 console.log('Saving not migrated list to failed.json:');221 notMigrated.forEach(console.log);222 fs.writeFileSync('./failed.json', JSON.stringify(notMigrated));223 process.exit(1);224 } else {225 console.log('Migration success');226 }227 }, options.wsEndpoint);228};229230const chunk = <T>(arr: T[], size: number) =>231 Array.from({length: Math.ceil(arr.length / size)}, (_: any, i: number) =>232 arr.slice(i * size, i * size + size));233234const testChainqlData = (data: any) => {235 const wrongData = [];236 for(const account of data) {237 try {238 if(account.address == null) throw Error('no address in data');239 if(account.balance == null) throw Error('no balance in data');240 if(account.account == null) throw Error('no account in data');241 if(account.account.fee_frozen == null) throw Error('no account.fee_frozen in data');242 if(account.account.misc_frozen == null) throw Error('no account.misc_frozen in data');243 if(account.account.free == null) throw Error('no account.free in data');244 if(account.account.reserved == null) throw Error('no account.reserved in data');245 if(account.locks == null) throw Error('no locks in data');246 if(account.locks[0].amount == null) throw Error('no locks.amount in data');247 if(account.locks[0].id == null) throw Error('no locks.id in data');248 } catch (error) {249 wrongData.push(account.address);250 console.log((error as Error).message, account.address);251 }252 if(wrongData.length > 0) {253 console.log(data);254 throw Error('Chainql data not correct');255 }256 }257 console.log('Chainql data correct');258};