Skip to content

Commit

Permalink
improve example contract
Browse files Browse the repository at this point in the history
  • Loading branch information
peterjah committed Aug 8, 2024
1 parent e7a5056 commit d35d293
Show file tree
Hide file tree
Showing 6 changed files with 78 additions and 35 deletions.
3 changes: 3 additions & 0 deletions packages/sc-project-initializer/commands/init/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
module.exports = {
extends: ['@massalabs'],
rules: {
'no-console': 'off',
},
};
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
import { stringToBytes } from '@massalabs/as-types';
import { event } from '../contracts/main';
import { Args, stringToBytes } from '@massalabs/as-types';
import { constructor, hello, NAME_KEY } from '../contracts/main';
import { setDeployContext, Storage } from '@massalabs/massa-as-sdk';

describe('Group test', () => {
test('Testing event', () => {
expect(event([])).toStrictEqual(stringToBytes("I'm an event!"));
const NAME = 'Massillian';

describe('SC unit tests', () => {
beforeAll(() => {
setDeployContext();
const args = new Args().add(NAME).serialize();
// init contract
constructor(args);
});

test('name is set', () => {
const name = Storage.get(NAME_KEY);
expect(name).toBe(NAME);
});

test('say hello', () => {
const expectedMessage = `Hello, ${NAME}!`;
expect(hello([])).toStrictEqual(stringToBytes(expectedMessage));
});
});
Original file line number Diff line number Diff line change
@@ -1,32 +1,36 @@
// The entry file of your WebAssembly module.
import { Context, generateEvent } from '@massalabs/massa-as-sdk';
import { Context, generateEvent, Storage } from '@massalabs/massa-as-sdk';
import { Args, stringToBytes } from '@massalabs/as-types';

export const NAME_KEY = 'name_key';

/**
* This function is meant to be called only one time: when the contract is deployed.
*
* @param binaryArgs - Arguments serialized with Args
*/
export function constructor(binaryArgs: StaticArray<u8>): StaticArray<u8> {
export function constructor(binaryArgs: StaticArray<u8>): void {
// This line is important. It ensures that this function can't be called in the future.
// If you remove this check, someone could call your constructor function and reset your smart contract.
if (!Context.isDeployingContract()) {
return [];
}
assert(Context.isDeployingContract());

const argsDeser = new Args(binaryArgs);
const name = argsDeser
.nextString()
.expect('Name argument is missing or invalid');

Storage.set(NAME_KEY, name);
generateEvent(`Constructor called with name ${name}`);
return [];
}

/**
* @param _ - not used
* @returns the emitted event serialized in bytes
*/
export function event(_: StaticArray<u8>): StaticArray<u8> {
const message = "I'm an event!";
export function hello(_: StaticArray<u8>): StaticArray<u8> {
assert(Storage.has(NAME_KEY), 'Name is not set');
const name = Storage.get(NAME_KEY);
const message = `Hello, ${name}!`;
generateEvent(message);
return stringToBytes(message);
}
1 change: 1 addition & 0 deletions packages/sc-project-initializer/commands/init/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"build": "massa-as-compile",
"clean": "rimraf build",
"deploy": "npm run build && tsx src/deploy.ts",
"hello": "tsx src/hello.ts",
"prettier": "prettier '**/src/**/*.ts' --check && as-prettier --check assembly",
"prettier:fix": "prettier '**/src/**/*.ts' --write && as-prettier --write assembly",
"lint": "eslint .",
Expand Down
41 changes: 19 additions & 22 deletions packages/sc-project-initializer/commands/init/src/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,32 +8,29 @@ import {
} from '@massalabs/massa-web3';
import { getScByteCode } from './utils';

async function deploy() {
const account = await Account.fromEnv();
const provider = Web3Provider.newPublicBuildnetProvider(account);
const account = await Account.fromEnv();
const provider = Web3Provider.newPublicBuildnetProvider(account);

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

const byteCode = getScByteCode('build', 'main.wasm');
const constructorArgs = new Args().addString('Massa');
const byteCode = getScByteCode('build', 'main.wasm');

const contract = await SmartContract.deploy(
provider,
byteCode,
constructorArgs,
{ coins: Mas.fromString('0.01') },
);
const name = 'Massa';
const constructorArgs = new Args().addString(name);

console.log('Contract deployed at:', contract.address);
const contract = await SmartContract.deploy(
provider,
byteCode,
constructorArgs,
{ coins: Mas.fromString('0.01') },
);

const events = await provider.getEvents({
smartContractAddress: contract.address,
isFinal: true,
});
console.log('Contract deployed at:', contract.address);

for (const event of events) {
console.log('Event: ', event.data);
}
}
const events = await provider.getEvents({
smartContractAddress: contract.address,
});

deploy();
for (const event of events) {
console.log('Event message:', event.data);
}
22 changes: 22 additions & 0 deletions packages/sc-project-initializer/commands/init/src/hello.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import {
Account,
bytesToStr,
SmartContract,
Web3Provider,
} from '@massalabs/massa-web3';
import 'dotenv/config'

// Paste the address of the deployed contract here
const CONTRACT_ADDR = 'AS12N5DvTVwvaLbaniMgDJqKwJ3uXBGwzzGuB1f6fjeSx3nhhahTE';

const account = await Account.fromEnv();
const provider = Web3Provider.newPublicBuildnetProvider(account);

const helloContract = new SmartContract(provider, CONTRACT_ADDR);

const messageBin = await helloContract.read('hello');

// deserialize message
const message = bytesToStr(messageBin.value);

console.log(`Received from the contract: ${message}`);

0 comments on commit d35d293

Please sign in to comment.