Skip to content

Commit

Permalink
prepare migration
Browse files Browse the repository at this point in the history
  • Loading branch information
peterjah committed Dec 12, 2024
1 parent 46df192 commit 8a29164
Show file tree
Hide file tree
Showing 10 changed files with 308 additions and 25 deletions.
61 changes: 60 additions & 1 deletion smart-contract/assembly/contracts/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
balance,
call,
functionExists,
generateEvent,
isDeployingContract,
setBytecode,
transferCoins,
Expand All @@ -22,10 +23,12 @@ import {
_update,
_constructor,
_ownerOf,
_increaseTotalSupply,
_getOwnedTokensKeyPrefix,
TOTAL_SUPPLY_KEY,
} from '@massalabs/sc-standards/assembly/contracts/MRC721/enumerable/MRC721Enumerable-internals';
// eslint-disable-next-line max-len
import { transferFrom as _transferFrom } from '@massalabs/sc-standards/assembly/contracts/MRC721/enumerable/MRC721Enumerable';

import {
_setOwner,
_onlyOwner,
Expand Down Expand Up @@ -458,6 +461,62 @@ export function transferFrom(binaryArgs: StaticArray<u8>): void {
_transferFrom(binaryArgs);
}

// TEMP CODE
const MIGRATE_COUNTER_KEY: StaticArray<u8> = [0x06];

function migrateCounterdKey(): StaticArray<u8> {
return DOMAIN_SEPARATOR_KEY.concat(MIGRATE_COUNTER_KEY);
}

export function migrate(_binaryArgs: StaticArray<u8>): void {
const BATCH_SIZE = 3000;

let migrateCounter = u256.Zero;
if (Storage.has(migrateCounterdKey())) {
migrateCounter = bytesToU256(Storage.get(migrateCounterdKey()));
}
if (!Storage.has(TOTAL_SUPPLY_KEY)) {
Storage.set(TOTAL_SUPPLY_KEY, u256ToBytes(u256.Zero));
}
const legacyCounter = bytesToU256(Storage.get(COUNTER_KEY)).toI32();

const migrateCountStart = migrateCounter.toI32();
let i = 0;
let tokenBalanceAdded = 0;
for (i = 0; i < BATCH_SIZE; i++) {
const tokenIdI32 = i + migrateCountStart;
const tokenId = u256.fromI32(tokenIdI32);

if (tokenIdI32 >= legacyCounter) {
generateEvent(`Reached total counter ${legacyCounter}`);
break;
}

const owner = _ownerOf(tokenId);
if (owner == '') {
generateEvent(`Token ${tokenIdI32} has no owner. Skipping.`);
continue;
}
tokenBalanceAdded += 1;

// not exported
// _addTokenToOwnerEnumeration(to, tokenId);
const key = _getOwnedTokensKeyPrefix(owner).concat(u256ToBytes(tokenId));
Storage.set(key, []);
}

_increaseTotalSupply(u256.fromI32(tokenBalanceAdded));

// update migration counter
Storage.set(
migrateCounterdKey(),
u256ToBytes(u256.fromI32(i + migrateCountStart)),
);
generateEvent(
`Migrated ${i} tokens. Total migrated: ${i + migrateCountStart}`,
);
}

export {
setOwner,
ownerAddress,
Expand Down
4 changes: 4 additions & 0 deletions smart-contract/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
"clean": "rimraf build",
"deploy": "npm run build && tsx src/deploy.ts",
"testDns": "tsx src/test.ts",
"info": "tsx src/infos.ts",
"migrate": "tsx src/migrate.ts",
"pause": "tsx src/pause.ts",
"unpause": "tsx src/unpause.ts",
"prettier": "prettier '**/src/**/*.ts' --check && as-prettier --check assembly",
"prettier:fix": "prettier '**/src/**/*.ts' --write && as-prettier --write assembly",
"lint": "eslint .",
Expand Down
6 changes: 6 additions & 0 deletions smart-contract/src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { MNS_CONTRACTS } from '@massalabs/massa-web3';

export const MNS_CONTRACT =
'AS12d2kZQYmGQRPmW7Axx5ysduAkPBR7bU86WemkkP4Lb9RSmZ13o';
// export const MNS_CONTRACT = MNS_CONTRACTS.buildnet;
export const IS_MAINNET = false;
37 changes: 21 additions & 16 deletions smart-contract/src/deploy.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,14 @@
import {
Account,
Args,
Mas,
SmartContract,
Web3Provider,
} from '@massalabs/massa-web3';
import { getScByteCode } from './utils';
import { config } from 'dotenv';
config();

const account = await Account.fromEnv();
const provider = Web3Provider.buildnet(account);
import { Args, Mas, SmartContract } from '@massalabs/massa-web3';
import { getScByteCode, initProvider } from './utils';

let op;
let events;

const provider = await initProvider();

console.log('Deploying contract...');

const byteCode = getScByteCode('build', 'main.wasm');
const byteCode = getScByteCode('build', 'legacy_mns.wasm');

const name = 'Massa';
const constructorArgs = new Args().addString(name);
Expand All @@ -23,15 +17,26 @@ const contract = await SmartContract.deploy(
provider,
byteCode,
constructorArgs,
{ coins: Mas.fromString('0.1'), waitFinalExecution: false },
{ coins: Mas.fromString('10'), waitFinalExecution: false },
);

console.log('Contract deployed at:', contract.address);

const events = await provider.getEvents({
events = await provider.getEvents({
smartContractAddress: contract.address,
});

for (const event of events) {
console.log('Event message:', event.data);
}

op = await contract.call('mintBatch', undefined, {
coins: Mas.fromString('70'),
});
events = await op.getSpeculativeEvents();

for (const event of events) {
console.log('mintBatch Events:', event.data);
}

console.log('mintBatch done ! operation:', op.id);
26 changes: 26 additions & 0 deletions smart-contract/src/infos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import {
getDomains,
getOwner,
getTokenCounter,
getTotalSupply,
initProvider,
} from './utils';
import { MNS_CONTRACT } from './config';

const provider = await initProvider();

const owner = await getOwner(provider);
console.log('Contract owner:', owner);

const count = await getTokenCounter(provider, MNS_CONTRACT);
console.log('COUNTER KEY:', count.toString());

const domainKeys = await getDomains(provider);
console.log('Total domains:', domainKeys.length);

try {
const totalSupply = await getTotalSupply(provider);
console.log('Total supply:', totalSupply.toString());
} catch (e) {
console.log('No total supply found');
}
57 changes: 57 additions & 0 deletions smart-contract/src/migrate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { SmartContract, Mas, Operation, rpcTypes } from '@massalabs/massa-web3';
import {
getMigrateCounter,
getScByteCode,
getTokenCounter,
initProvider,
} from './utils';
import { MNS_CONTRACT } from './config';

const provider = await initProvider();

const byteCode = getScByteCode('build', 'main.wasm');
const contract = new SmartContract(provider, MNS_CONTRACT);

// todo: pause contract

let op: Operation;
let events: rpcTypes.OutputEvents;
op = await contract.call('upgradeSC', byteCode, {
coins: Mas.fromString('3'),
fee: Mas.fromString('0.1'),
});
events = await op.getFinalEvents();

for (const event of events) {
console.log('upgradeSC Events:', event.data);
}

console.log('upgradeSC done ! operation:', op.id);

const counter = await getTokenCounter(provider, MNS_CONTRACT);
let migrateCount = 0n;
try {
migrateCount = await getMigrateCounter(provider, MNS_CONTRACT);
} catch (e) {
console.log('no migrate counter found');
}

while (migrateCount < counter) {
console.log('migrating batch from tokenID', migrateCount.toString());
op = await contract.call('migrate', undefined, {
coins: Mas.fromString('20'),
fee: Mas.fromString('0.1'),
});

events = await op.getFinalEvents();

for (const event of events) {
console.log('migrate Events:', event.data);
}
migrateCount = await getMigrateCounter(provider, MNS_CONTRACT);
console.log('new migrate count:', migrateCount.toString());
}

// unpause contract

console.log('Upgrade done ! operation:');
16 changes: 16 additions & 0 deletions smart-contract/src/pause.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { SmartContract } from '@massalabs/massa-web3';
import { initProvider } from './utils';
import { MNS_CONTRACT } from './config';

const provider = await initProvider();

const contract = new SmartContract(provider, MNS_CONTRACT);

const op = await contract.call('dnsLock', undefined, { coins: 100000000n });
const events = await op.getSpeculativeEvents();

for (const event of events) {
console.log('pause Events:', event.data);
}

console.log('Contract paused ! operation:', op.id);
47 changes: 39 additions & 8 deletions smart-contract/src/test.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
import { Account, Web3Provider, MNS } from '@massalabs/massa-web3';
import { config } from 'dotenv';
config();
import { MNS, strToBytes, bytesToStr } from '@massalabs/massa-web3';
import { DOMAIN_SEPARATOR_KEY, initProvider } from './utils';
import { MNS_CONTRACT } from './config';

const MNS_CONTRACT = 'AS1qyye6EfPSvj8whjEeUCZepD3mnhYvaaLub65DGcF6jdxydBPs';
const provider = await initProvider();

const account = await Account.fromEnv();
const provider = Web3Provider.buildnet(account);
const MNSContract = new MNS(provider, MNS_CONTRACT);

// Claim dns
const domain = 'testaurelienlol';
const domain = 'testaurelienlolloulilolsdsdssdsd';

const op = await MNSContract.alloc(domain, provider.address, {
coins: BigInt(1043000000),
coins: BigInt(2000000000),
});

const events = await op.getSpeculativeEvents();
Expand All @@ -27,3 +25,36 @@ if (domainOwner === provider.address) {
} else {
console.error('KO! Domain is not owned by the current account');
}

// get owned tokens
const OWNED_TOKENS_KEY = strToBytes('ownedTokens');
const OWNED_FILTER = Uint8Array.from([
...OWNED_TOKENS_KEY,
...strToBytes(provider.address),
]);
const ownedkeys = await provider.getStorageKeys(
MNS_CONTRACT,
OWNED_FILTER,
false,
);
console.log('Nb owned tokens:', ownedkeys.length);
const domainKeys = ownedkeys.map((k) => {
const tokenIdBytes = k.slice(OWNED_FILTER.length);
const DOMAIN_KEY_PREFIX = [0x03];

return Uint8Array.from([
...DOMAIN_SEPARATOR_KEY,
...DOMAIN_KEY_PREFIX,
...tokenIdBytes,
]);
});
const domainsBytes = await provider.readStorage(
MNS_CONTRACT,
domainKeys,
false,
);
const domains = domainsBytes.map((d) => bytesToStr(d));
console.log('Owned domains:', domains);
if (!domains.includes(domain)) {
console.error('KO! Domain is not in the owned domains');
}
15 changes: 15 additions & 0 deletions smart-contract/src/unpause.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { SmartContract } from '@massalabs/massa-web3';
import { initProvider } from './utils';
import { MNS_CONTRACT } from './config';

const provider = await initProvider();
const contract = new SmartContract(provider, MNS_CONTRACT);

const op = await contract.call('dnsUnlock');
const events = await op.getSpeculativeEvents();

for (const event of events) {
console.log('Unpause Events:', event.data);
}

console.log('Contract unpaused ! operation:', op.id);
Loading

0 comments on commit 8a29164

Please sign in to comment.