Skip to content

Commit

Permalink
Implement Random Number example
Browse files Browse the repository at this point in the history
  • Loading branch information
Swafox committed Apr 6, 2024
1 parent 1cde34f commit c202a73
Show file tree
Hide file tree
Showing 6 changed files with 157 additions and 94 deletions.
1 change: 1 addition & 0 deletions .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ jobs:
- BasicFunctions
- BlankProject
- SimpleCounter
- Mathematics

steps:
- uses: actions/checkout@v3
Expand Down
13 changes: 13 additions & 0 deletions Mathematics/contracts/mathematics.fc
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,19 @@ global int ctx_counter;
return ();
}

;; How to generate random number
;; Cookbook link: https://docs.ton.org/develop/func/cookbook#how-to-generate-random-number
;; Random number generation: https://docs.ton.org/develop/smart-contracts/guidelines/random-number-generation
if (op == 2) {
randomize_lt(); ;; do this once
int a = rand(10);

ctx_counter += a;

save_data();
return ();
}

throw(777);
}

Expand Down
29 changes: 28 additions & 1 deletion Mathematics/tests/Mathematics.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ describe("Mathematics", () => {
// blockchain and mathematics are ready to use
});

it("should increase counter", async () => {
it("Nth Power: should increase counter", async () => {
const increaser = await blockchain.treasury("increaserRandom");

const counterBefore = await mathematics.getCounter();
Expand Down Expand Up @@ -73,4 +73,31 @@ describe("Mathematics", () => {

expect(counterAfter).toBe(counterBefore + increaseBy ** 3);
});

it("Random: should increase counter", async () => {
const increaser = await blockchain.treasury("increaserRandom");

const counterBefore = await mathematics.getCounter();

console.log("counter before increasing", counterBefore);

const increaseResult = await mathematics.sendRandom(
increaser.getSender(),
{
value: toNano("0.05"),
},
);

expect(increaseResult.transactions).toHaveTransaction({
from: increaser.address,
to: mathematics.address,
success: true,
});

const counterAfter = await mathematics.getCounter();

console.log("counter after increasing", counterAfter);

expect(counterAfter).toBeGreaterThan(counterBefore);
});
});
14 changes: 14 additions & 0 deletions Mathematics/wrappers/Mathematics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,20 @@ export class Mathematics implements Contract {
});
}

async sendRandom(
provider: ContractProvider,
via: Sender,
opts: {
value: bigint;
},
) {
await provider.internal(via, {
value: opts.value,
sendMode: SendMode.PAY_GAS_SEPARATELY,
body: beginCell().storeUint(2, 32).storeUint(1, 32).endCell(),
});
}

async getCounter(provider: ContractProvider) {
const result = await provider.get("get_counter", []);
return result.stack.readNumber();
Expand Down
54 changes: 28 additions & 26 deletions SimpleCounter/scripts/incrementSimpleCounter.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,39 @@
import { Address, toNano } from '@ton/core';
import { SimpleCounter } from '../wrappers/SimpleCounter';
import { NetworkProvider, sleep } from '@ton/blueprint';
import { Address, toNano } from "@ton/core";
import { SimpleCounter } from "../wrappers/SimpleCounter";
import { NetworkProvider, sleep } from "@ton/blueprint";

export async function run(provider: NetworkProvider, args: string[]) {
const ui = provider.ui();
const ui = provider.ui();

const address = Address.parse(args.length > 0 ? args[0] : await ui.input('SimpleCounter address'));
const address = Address.parse(
args.length > 0 ? args[0] : await ui.input("SimpleCounter address"),
);

if (!(await provider.isContractDeployed(address))) {
ui.write(`Error: Contract at address ${address} is not deployed!`);
return;
}
if (!(await provider.isContractDeployed(address))) {
ui.write(`Error: Contract at address ${address} is not deployed!`);
return;
}

const simpleCounter = provider.open(SimpleCounter.createFromAddress(address));
const simpleCounter = provider.open(SimpleCounter.createFromAddress(address));

const counterBefore = await simpleCounter.getCounter();
const counterBefore = await simpleCounter.getCounter();

await simpleCounter.sendIncrease(provider.sender(), {
increaseBy: 1,
value: toNano('0.05'),
});
await simpleCounter.sendIncrease(provider.sender(), {
increaseBy: 1,
value: toNano("0.05"),
});

ui.write('Waiting for counter to increase...');
ui.write("Waiting for counter to increase...");

let counterAfter = await simpleCounter.getCounter();
let attempt = 1;
while (counterAfter === counterBefore) {
ui.setActionPrompt(`Attempt ${attempt}`);
await sleep(2000);
counterAfter = await simpleCounter.getCounter();
attempt++;
}
let counterAfter = await simpleCounter.getCounter();
let attempt = 1;
while (counterAfter === counterBefore) {
ui.setActionPrompt(`Attempt ${attempt}`);
await sleep(2000);
counterAfter = await simpleCounter.getCounter();
attempt++;
}

ui.clearActionPrompt();
ui.write('Counter increased successfully!');
ui.clearActionPrompt();
ui.write("Counter increased successfully!");
}
140 changes: 73 additions & 67 deletions SimpleCounter/tests/SimpleCounter.spec.ts
Original file line number Diff line number Diff line change
@@ -1,81 +1,87 @@
import { Blockchain, SandboxContract, TreasuryContract } from '@ton/sandbox';
import { Cell, toNano } from '@ton/core';
import { SimpleCounter } from '../wrappers/SimpleCounter';
import '@ton/test-utils';
import { compile } from '@ton/blueprint';

describe('SimpleCounter', () => {
let code: Cell;

beforeAll(async () => {
code = await compile('SimpleCounter');
});

let blockchain: Blockchain;
let deployer: SandboxContract<TreasuryContract>;
let simpleCounter: SandboxContract<SimpleCounter>;

beforeEach(async () => {
blockchain = await Blockchain.create();

simpleCounter = blockchain.openContract(
SimpleCounter.createFromConfig(
{
id: 0,
counter: 0,
},
code
)
);

deployer = await blockchain.treasury('deployer');

const deployResult = await simpleCounter.sendDeploy(deployer.getSender(), toNano('0.05'));

expect(deployResult.transactions).toHaveTransaction({
from: deployer.address,
to: simpleCounter.address,
deploy: true,
success: true,
});
import { Blockchain, SandboxContract, TreasuryContract } from "@ton/sandbox";
import { Cell, toNano } from "@ton/core";
import { SimpleCounter } from "../wrappers/SimpleCounter";
import "@ton/test-utils";
import { compile } from "@ton/blueprint";

describe("SimpleCounter", () => {
let code: Cell;

beforeAll(async () => {
code = await compile("SimpleCounter");
});

let blockchain: Blockchain;
let deployer: SandboxContract<TreasuryContract>;
let simpleCounter: SandboxContract<SimpleCounter>;

beforeEach(async () => {
blockchain = await Blockchain.create();

simpleCounter = blockchain.openContract(
SimpleCounter.createFromConfig(
{
id: 0,
counter: 0,
},
code,
),
);

deployer = await blockchain.treasury("deployer");

const deployResult = await simpleCounter.sendDeploy(
deployer.getSender(),
toNano("0.05"),
);

expect(deployResult.transactions).toHaveTransaction({
from: deployer.address,
to: simpleCounter.address,
deploy: true,
success: true,
});
});

it('should deploy', async () => {
// the check is done inside beforeEach
// blockchain and simpleCounter are ready to use
});
it("should deploy", async () => {
// the check is done inside beforeEach
// blockchain and simpleCounter are ready to use
});

it('should increase counter', async () => {
const increaseTimes = 3;
for (let i = 0; i < increaseTimes; i++) {
console.log(`increase ${i + 1}/${increaseTimes}`);
it("should increase counter", async () => {
const increaseTimes = 3;
for (let i = 0; i < increaseTimes; i++) {
console.log(`increase ${i + 1}/${increaseTimes}`);

const increaser = await blockchain.treasury('increaser' + i);
const increaser = await blockchain.treasury("increaser" + i);

const counterBefore = await simpleCounter.getCounter();
const counterBefore = await simpleCounter.getCounter();

console.log('counter before increasing', counterBefore);
console.log("counter before increasing", counterBefore);

const increaseBy = Math.floor(Math.random() * 100);
const increaseBy = Math.floor(Math.random() * 100);

console.log('increasing by', increaseBy);
console.log("increasing by", increaseBy);

const increaseResult = await simpleCounter.sendIncrease(increaser.getSender(), {
increaseBy,
value: toNano('0.05'),
});
const increaseResult = await simpleCounter.sendIncrease(
increaser.getSender(),
{
increaseBy,
value: toNano("0.05"),
},
);

expect(increaseResult.transactions).toHaveTransaction({
from: increaser.address,
to: simpleCounter.address,
success: true,
});
expect(increaseResult.transactions).toHaveTransaction({
from: increaser.address,
to: simpleCounter.address,
success: true,
});

const counterAfter = await simpleCounter.getCounter();
const counterAfter = await simpleCounter.getCounter();

console.log('counter after increasing', counterAfter);
console.log("counter after increasing", counterAfter);

expect(counterAfter).toBe(counterBefore + increaseBy);
}
});
expect(counterAfter).toBe(counterBefore + increaseBy);
}
});
});

0 comments on commit c202a73

Please sign in to comment.