Skip to content

Commit

Permalink
temp
Browse files Browse the repository at this point in the history
  • Loading branch information
eshaan7 committed Aug 7, 2024
1 parent 68a9a73 commit 51b4218
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 147 deletions.
Binary file added Avail unification cup MRU.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
27 changes: 12 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import express, { Request, Response } from "express";

import {
ActionConfirmationStatus,
ActionExecutionStatus,
MicroRollup,
} from "@stackr/sdk";
import dotenv from "dotenv";
import { stackrConfig } from "../stackr.config.ts";
import { schemas } from "./stackr/actions.ts";
Expand All @@ -15,18 +19,12 @@ import {
LogAction,
transitions,
} from "./stackr/transitions.ts";

dotenv.config();

import {
ActionConfirmationStatus,
ActionExecutionStatus,
MicroRollup,
} from "@stackr/sdk";
import { Logs, Player } from "./stackr/state.ts";
import { PlayerStats } from "./types.ts";
import { getActionInfo } from "./utils.ts";

dotenv.config();

export const stfSchemaMap = {
startTournament: schemas.startTournament,
startMatch: schemas.startMatch,
Expand All @@ -52,10 +50,14 @@ const main = async () => {
actionSchemas: Object.values(schemas),
stateMachines: [leagueMachine],
stfSchemaMap,
isSandbox: process.env.NODE_ENV === "sandbox",
});

await mru.init();
const machine = mru.stateMachines.get<LeagueMachine>(STATE_MACHINES.LEAGUE);

if (!machine) {
throw new Error("League machine not initialized yet");
}

const app = express();
app.use(express.json());
Expand All @@ -69,11 +71,6 @@ const main = async () => {
next();
});

const machine = mru.stateMachines.get<LeagueMachine>(STATE_MACHINES.LEAGUE);

if (!machine) {
throw new Error("League machine not initialized yet");
}

const getMatchInfo = (matchId: number) => {
const { teams, matches } = machine.state;
Expand Down
30 changes: 14 additions & 16 deletions src/stackr/state.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { State } from "@stackr/sdk/machine";
import { keccak256, solidityPacked } from "ethers";
import { createMMR, createMT } from "./utils";
import { solidityPacked, solidityPackedKeccak256 } from "ethers";
import { createMT } from "./utils";

type TournamentMeta = {
round: number;
Expand Down Expand Up @@ -72,7 +72,7 @@ export class League extends State<LeagueState> {
)
);

const matchesMMR = createMMR(matches, (m) => {
const matchesMMR = createMT(matches, (m) => {
const teamIds = Object.keys(m.scores).map((k) => parseInt(k));
const scores = teamIds.map((id) => m.scores[id]);
return solidityPacked(
Expand Down Expand Up @@ -101,25 +101,23 @@ export class League extends State<LeagueState> {
);
});

const logsMMR = createMMR(logs, (l) =>
const logsMMR = createMT(logs, (l) =>
solidityPacked(
["uint256", "uint256", "string", "uint256"],
[l.playerId, l.timestamp, l.action, l.matchId || 0]
)
);

const metaHash = keccak256(
solidityPacked(
["uint256", "uint256", "uint256", "uint256", "string"],
Object.values(meta).map((v) => {
if (typeof v === "number") {
return v;
}
return Object.entries(v)
.map(([k, v]) => `${k}:${v}`)
.join(",");
})
)
const metaHash = solidityPackedKeccak256(
["uint256", "uint256", "uint256", "uint256", "string"],
Object.values(meta).map((v) => {
if (typeof v === "number") {
return v;
}
return Object.entries(v)
.map(([k, v]) => `${k}:${v}`)
.join(",");
})
);

const finalMerkleTree = createMT([
Expand Down
118 changes: 2 additions & 116 deletions src/stackr/utils.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,5 @@
import {
hexlify,
isHexString,
keccak256,
solidityPackedKeccak256,
ZeroHash,
} from "ethers";
import { MerkleMountainRange, MerkleTree } from "merkletreejs";

export interface MMRResponse {
rootHash: string;
merkleProof: (leaf: string) =>
| {
root: string;
width: number;
index: number;
peakBagging: string[];
siblings: string[];
}
| undefined;
verifyProof: (
leafIndex: number,
leaf: string,
width: number,
peakBagging: string[],
siblings: string[]
) => boolean;
}
import { keccak256, ZeroHash } from "ethers";
import { MerkleTree } from "merkletreejs";

export interface MTResponse {
rootHash: string;
Expand All @@ -38,94 +12,6 @@ export interface MTResponse {
verifyProof: (leaf: string, proof: string[]) => boolean;
}

const hashLeafFn = (index: number, dataHash: Buffer): string =>
solidityPackedKeccak256(["uint256", "bytes32"], [index, hexlify(dataHash)]);

const peakBaggingFn = (size: number, peaks: Buffer[]): string =>
solidityPackedKeccak256(
["uint256", "bytes32"],
[
size,
solidityPackedKeccak256(
["uint256", "bytes32[]"],
[size, peaks.map((peak) => hexlify(peak))]
),
]
);

const hashBranchFn = (index: number, left: Buffer, right: Buffer): string =>
solidityPackedKeccak256(
["uint256", "bytes32", "bytes32"],
[index, hexlify(left), hexlify(right)]
);

/**
* 7
* 3 6 10
* 1 2 4 5 8 9 11
* 1 2 3 4 5 6 7
* @param items List of items to be included in the Merkle Mountain Range
* @param serializer Optional function to serialize the items
* @returns `MMRResponse` object
*/
export const createMMR = <ConvertibleItem>(
items: ConvertibleItem[],
serializer?: (item: ConvertibleItem) => string
): MMRResponse => {
const mmr = new MerkleMountainRange(
keccak256,
serializer ? items.map(serializer) : items,
hashLeafFn,
peakBaggingFn,
hashBranchFn
);

const rootHash = mmr.getHexRoot();

return {
rootHash: rootHash === "0x" ? ZeroHash : rootHash,
merkleProof: (leaf: string) => {
const hashes = Object.keys(mmr.data);
const itemIndex = hashes.indexOf(keccak256(leaf));
if (itemIndex === -1) {
// Leaf not found
return undefined;
}
const leafIndex = mmr.getLeafIndex(itemIndex + 1); // indexing in tree starts from 1
const mmrProof = mmr.getMerkleProof(leafIndex);
return {
root: mmr.bufferToHex(mmrProof.root),
width: mmrProof.width,
index: leafIndex,
peakBagging: mmrProof.peakBagging.map((peak) => mmr.bufferToHex(peak)),
siblings: mmrProof.siblings.map((sibling) => mmr.bufferToHex(sibling)),
};
},
verifyProof: (
leafIndex: number,
leaf: string,
width: number,
peaks: string[],
siblings: string[]
): boolean => {
try {
return mmr.verify(
mmr.getRoot(),
width,
leafIndex,
leaf,
peaks.map((peak) => (isHexString(peak) ? mmr.bufferify(peak) : peak)),
siblings.map((sibling) =>
isHexString(sibling) ? mmr.bufferify(sibling) : sibling
)
);
} catch (error) {
return false;
}
},
};
};

/**
* @param items List of items to be included in the Merkle Tree
* @param serializer Optional function to serialize the items
Expand Down

0 comments on commit 51b4218

Please sign in to comment.