Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Twl/some of them intermediate sortkey commits se #462

Merged
merged 6 commits into from
Sep 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@ module.exports = {
'^.+\\.(ts|js)$': 'ts-jest'
},

silent: false
silent: true
};
5 changes: 5 additions & 0 deletions src/__tests__/integration/data/example-contract.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,14 @@ export async function handle(state, action) {

if (action.input.function === 'add') {
state.counter++;
if (action.input.throw) {
throw new ContractError('Error from "add" function');
}
return { state };
}

if (action.input.function === 'addAndWrite') {
console.log("addAndWrite");
const result = await SmartWeave.contracts.write(action.input.contractId, {
function: 'addAmount',
amount: action.input.amount
Expand Down Expand Up @@ -51,4 +55,5 @@ export async function handle(state, action) {
if (action.input.function === 'justThrow') {
throw new ContractError('Error from justThrow function');
}

}
2 changes: 2 additions & 0 deletions src/__tests__/integration/data/kv-storage-inner-calls.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@ export async function handle(state, action) {
target: input.target,
qty: input.qty
});

return {state};
}

if (input.function === 'innerViewKV') {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"ticker": "LEAF_TOKEN",
"balances": {
"asd": 100
}
}
22 changes: 22 additions & 0 deletions src/__tests__/integration/data/nested-read/leaf-contract.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export async function handle(state, action) {
const balances = state.balances;
const input = action.input;

if (input.function === "increase") {
const target = input.target;
const qty = input.qty;

balances[target] += qty;

return { state };
}

if (input.function === "balance") {
const target = input.target;
const ticker = state.ticker;

return { result: { target, ticker, balance: balances[target] } };
}

throw new ContractError(`No function supplied or function not recognised: "${input.function}"`);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"ticker": "NODE",
"balances": {
}
}
24 changes: 24 additions & 0 deletions src/__tests__/integration/data/nested-read/node-contract.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
export async function handle(state, action) {
const balances = state.balances;
const input = action.input;


if (input.function === "balance") {
const target = input.target;
const ticker = state.ticker;

return { result: { target, ticker, balance: balances[target] } };
}

if (input.function === "readBalanceFrom") {
let token = input.tokenAddress;
let tx = input.contractTxId;

const result = await SmartWeave.contracts.readContractState(token);

balances[tx] = result.balances[tx];
return { state };
}

throw new ContractError(`No function supplied or function not recognised: "${input.function}"`);
}
2 changes: 2 additions & 0 deletions src/__tests__/integration/data/writing-contract.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,8 @@ export async function handle(state, action) {
}

if (action.input.function === 'addAmount') {
console.log("addAmount", action.input);

state.counter += action.input.amount;
return { state };
}
Expand Down
187 changes: 187 additions & 0 deletions src/__tests__/integration/internal-writes/internal-nested-read.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
import fs from 'fs';

import ArLocal from 'arlocal';
import { JWKInterface } from 'arweave/node/lib/wallet';
import path from 'path';
import { mineBlock } from '../_helpers';
import { Contract } from '../../../contract/Contract';
import { Warp } from '../../../core/Warp';
import { WarpFactory } from "../../../core/WarpFactory";
import { LoggerFactory } from '../../../logging/LoggerFactory';
import { DeployPlugin } from "warp-contracts-plugin-deploy";

/**
* This test verifies "deep" reads between contracts.
*
*
* rootContract
* └───► node1Contract
* └───► node20Contract
* └───► leafContract: balances['asd'] = 300
* └───► node21Contract
* └───► leafContract: balances['asd'] = 1350
* └───► node22Contract
* └───► leafContract: balances['asd'] = 1100
*
*/
describe('Testing deep internal reads', () => {
let wallet: JWKInterface;

let arLocal: ArLocal;
let warp: Warp;
let leafContract: Contract<any>;
let node20Contract: Contract<any>;
let node21Contract: Contract<any>;
let node22Contract: Contract<any>;
let node1Contract: Contract<any>;
let rootContract: Contract<any>;

let leafId;
let node20Id;
let node21Id;
let node22Id;
let nod1Id;
let rootId;

const port = 1932;

beforeAll(async () => {
arLocal = new ArLocal(port, false);
await arLocal.start();
LoggerFactory.INST.logLevel('info');
});

afterAll(async () => {
await arLocal.stop();
});

async function deployContracts() {
warp = WarpFactory.forLocal(port).use(new DeployPlugin());

({ jwk: wallet } = await warp.generateWallet());

const leafSrc = fs.readFileSync(path.join(__dirname, '../data/nested-read/leaf-contract.js'), 'utf8');
const leafState = fs.readFileSync(path.join(__dirname, '../data/nested-read/leaf-contract-init-state.json'), 'utf8');
const nodeSrc = fs.readFileSync(path.join(__dirname, '../data/nested-read/node-contract.js'), 'utf8');
const nodeState = fs.readFileSync(path.join(__dirname, '../data/nested-read/node-contract-init-state.json'), 'utf8');

({ contractTxId: leafId } = await warp.deploy({
wallet,
initState: leafState,
src: leafSrc
}));

({ contractTxId: node20Id } = await warp.deploy({
wallet,
initState: nodeState,
src: nodeSrc
}));

({ contractTxId: node21Id } = await warp.deploy({
wallet,
initState: nodeState,
src: nodeSrc
}));

({ contractTxId: node22Id } = await warp.deploy({
wallet,
initState: nodeState,
src: nodeSrc
}));

({ contractTxId: nod1Id } = await warp.deploy({
wallet,
initState: nodeState,
src: nodeSrc
}));

({ contractTxId: rootId } = await warp.deploy({
wallet,
initState: nodeState,
src: nodeSrc
}));

rootContract = warp
.contract(rootId)
.connect(wallet);
node20Contract = warp
.contract(node20Id)
.connect(wallet);
node21Contract = warp
.contract(node21Id)
.connect(wallet);
node22Contract = warp
.contract(node22Id)
.connect(wallet);
node1Contract = warp
.contract(nod1Id)
.connect(wallet);
leafContract = warp
.contract(leafId)
.connect(wallet);

await mineBlock(warp);
await mineBlock(warp);
}

describe('with the same leaf contract', () => {
beforeAll(async () => {
await deployContracts();
});

it('root contract should have the latest balance', async () => {
await leafContract.writeInteraction({ function: 'increase', target: 'asd', qty: 25 });
await leafContract.writeInteraction({ function: 'increase', target: 'asd', qty: 25 });
await leafContract.writeInteraction({ function: 'increase', target: 'asd', qty: 50 });
await leafContract.writeInteraction({ function: 'increase', target: 'asd', qty: 50 });
await leafContract.writeInteraction({ function: 'increase', target: 'asd', qty: 50 });
await mineBlock(warp);
await node20Contract.writeInteraction({ function: 'readBalanceFrom', tokenAddress: leafId, contractTxId: 'asd' });
await mineBlock(warp);
await leafContract.writeInteraction({ function: 'increase', target: 'asd', qty: 200 });
await leafContract.writeInteraction({ function: 'increase', target: 'asd', qty: 100 });
await leafContract.writeInteraction({ function: 'increase', target: 'asd', qty: 100 });
await mineBlock(warp);
await leafContract.writeInteraction({ function: 'increase', target: 'asd', qty: 100 });
await mineBlock(warp);
await leafContract.writeInteraction({ function: 'increase', target: 'asd', qty: 100 });
await mineBlock(warp);
await leafContract.writeInteraction({ function: 'increase', target: 'asd', qty: 100 });
await mineBlock(warp);
await leafContract.writeInteraction({ function: 'increase', target: 'asd', qty: 100 });
await mineBlock(warp);
await node22Contract.writeInteraction({ function: 'readBalanceFrom', tokenAddress: leafId, contractTxId: 'asd' });
await mineBlock(warp);
await leafContract.writeInteraction({ function: 'increase', target: 'asd', qty: 50 });
await leafContract.writeInteraction({ function: 'increase', target: 'asd', qty: 100 });
await leafContract.writeInteraction({ function: 'increase', target: 'asd', qty: 100 });
await mineBlock(warp);
await node21Contract.writeInteraction({ function: 'readBalanceFrom', tokenAddress: leafId, contractTxId: 'asd' });
await mineBlock(warp);
await node1Contract.writeInteraction({ function: 'readBalanceFrom', tokenAddress: node20Id, contractTxId: 'asd' });
await mineBlock(warp);
await node1Contract.writeInteraction({ function: 'readBalanceFrom', tokenAddress: node21Id, contractTxId: 'asd' });
await mineBlock(warp);
await node1Contract.writeInteraction({ function: 'readBalanceFrom', tokenAddress: node22Id, contractTxId: 'asd' });
await mineBlock(warp);
await rootContract.writeInteraction({ function: 'readBalanceFrom', tokenAddress: nod1Id, contractTxId: 'asd' });
await mineBlock(warp);


const rootResult = await warp.pst(rootId)
.setEvaluationOptions({
cacheEveryNInteractions: 1,
}).readState();
expect(rootResult.cachedValue.state.balances['asd']).toEqual(1100);

const node20Result = await warp.pst(node20Id).readState();
expect(node20Result.cachedValue.state.balances['asd']).toEqual(300);

const node21Result = await warp.pst(node21Id).readState();
expect(node21Result.cachedValue.state.balances['asd']).toEqual(1350);

const node22Result = await warp.pst(node22Id).readState();
expect(node22Result.cachedValue.state.balances['asd']).toEqual(1100);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { WarpFactory } from '../../../core/WarpFactory';
import { LoggerFactory } from '../../../logging/LoggerFactory';
import { DeployPlugin } from 'warp-contracts-plugin-deploy';
import { VM2Plugin } from 'warp-contracts-plugin-vm2';
import { MemoryLevel } from 'memory-level';

interface ExampleContractState {
counter: number;
Expand Down Expand Up @@ -213,6 +214,85 @@ describe('Testing internal writes', () => {
});
});

describe('should properly commit states', () => {
beforeAll(async () => {
await deployContracts();
});

async function currentContractEntries(contractTxId: string): Promise<[[string, string]]> {
const storage: MemoryLevel<string, any> = await warp.stateEvaluator.getCache().storage();
const sub = storage.sublevel(contractTxId, { valueEncoding: "json" });
return await sub.iterator().all();
}

it('should write to cache the initial state', async () => {
expect((await calleeContract.readState()).cachedValue.state.counter).toEqual(555);
await mineBlock(warp);
const entries = await currentContractEntries(calleeContract.txId());
expect(entries.length).toEqual(1);
});

it('should write to cache at the end of evaluation (if no interactions with other contracts)', async () => {
await calleeContract.writeInteraction({ function: 'add' });
await calleeContract.writeInteraction({ function: 'add' });
await calleeContract.writeInteraction({ function: 'add' });
await calleeContract.writeInteraction({ function: 'add' });
await mineBlock(warp);
const entries1 = await currentContractEntries(calleeContract.txId());
expect(entries1.length).toEqual(1);

await calleeContract.readState();
const entries2 = await currentContractEntries(calleeContract.txId());
expect(entries2.length).toEqual(2);

await calleeContract.writeInteraction({ function: 'add' });
await calleeContract.writeInteraction({ function: 'add' });
await mineBlock(warp);
const entries3 = await currentContractEntries(calleeContract.txId());
expect(entries3.length).toEqual(2);

await calleeContract.readState();
const entries4 = await currentContractEntries(calleeContract.txId());
expect(entries4.length).toEqual(3);
});

// i.e. it should write the state from previous sort key under the sort key of the last interaction
it('should rollback state', async () => {
await calleeContract.writeInteraction({ function: 'add' });
await mineBlock(warp);
const result1 = await calleeContract.readState();
const entries1 = await currentContractEntries(calleeContract.txId());
expect(entries1.length).toEqual(4);
await calleeContract.writeInteraction({ function: 'add', throw: true });
await mineBlock(warp);

await calleeContract.readState();
const entries2 = await currentContractEntries(calleeContract.txId());
expect(entries2.length).toEqual(5);
const lastCacheValue = await warp.stateEvaluator.getCache().getLast(calleeContract.txId());
expect(lastCacheValue.cachedValue.state).toEqual(result1.cachedValue.state);
expect(Object.keys(result1.cachedValue.errorMessages).length + 1).toEqual(Object.keys(lastCacheValue.cachedValue.errorMessages).length);

const blockHeight = (await warp.arweave.network.getInfo()).height;
expect(lastCacheValue.sortKey).toContain(`${blockHeight}`.padStart(12, '0'));
});

it('should write to cache at the end of interaction (if interaction with other contracts)', async () => {
await calleeContract.writeInteraction({ function: 'add' });
await mineBlock(warp);

// this writeInteraction will cause the state with the previous 'add' to be added the cache
// - hence the 7 (not 6) entries in the cache at the end of this test
await calleeContract.writeInteraction({ function: 'addAndWrite', contractId: callingContract.txId(), amount: 1 });
await mineBlock(warp);

await calleeContract.readState();
const entries2 = await currentContractEntries(calleeContract.txId());
expect(entries2.length).toEqual(7);
});

});

describe('with read state at the end', () => {
beforeAll(async () => {
await deployContracts();
Expand Down
Loading