Compare commits

...

7 Commits

34 changed files with 1878 additions and 247 deletions

26
backend/.gitignore vendored Normal file
View File

@ -0,0 +1,26 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
secrets.*

13
backend/api_entrypoint.ts Normal file
View File

@ -0,0 +1,13 @@
import { api } from "./src/api";
import { CONFIG } from "./src/config";
import { connectToDb } from "./src/db";
async function bootstrap() {
await connectToDb();
api.listen(CONFIG.API_PORT, () =>
console.log(`⚙️ Listening on :${CONFIG.API_PORT}`)
);
}
bootstrap();

26
backend/package.json Normal file
View File

@ -0,0 +1,26 @@
{
"name": "osipad-backend",
"version": "1.0.0",
"description": "",
"main": "index.ts",
"scripts": {
"api:dev": "nodemon api_entrypoint.ts",
"api:prod": "ts-node api_entrypoint.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.19.2",
"mongoose": "^8.4.0"
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/node": "^20.12.11",
"nodemon": "^3.1.0",
"ts-node": "^10.9.2",
"typescript": "^5.4.5"
}
}

1052
backend/pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,37 @@
import { RequestHandler } from "express";
import { Campaign } from "../../db/campaign";
export const getMany: RequestHandler = async (req, res, next) => {
try {
const campaigns = await Campaign.find();
return res.json({
ok: true,
data: campaigns,
});
} catch (error) {
return next(error);
}
};
export const create: RequestHandler = async (req, res, next) => {
try {
const { name, contractAddress } = req.body;
if (!name || !contractAddress) {
throw new Error("Missing field(s).");
}
const campaign = new Campaign({
name: req.body.name,
contractAddress: req.body.contractAddress,
});
await campaign.save();
return res.json({
ok: true,
data: campaign,
});
} catch (error) {
return next(error);
}
};

View File

@ -0,0 +1,7 @@
import { RequestHandler } from "express";
export const getIndex: RequestHandler = async (req, res) => {
return res.json({
message: "It works!",
});
};

24
backend/src/api/index.ts Normal file
View File

@ -0,0 +1,24 @@
import cors from "cors";
import express, { ErrorRequestHandler } from "express";
import { campaignsRouter } from "./routes/campaigns";
import { testRouter } from "./routes/test";
export const api = express();
// Middleware
api.use(cors());
api.use(express.json());
// Routes
api.use("/test", testRouter);
api.use("/campaigns", campaignsRouter);
// Error Handler
const errorHandler: ErrorRequestHandler = (error, req, res, next) => {
console.error(error);
return res.json({
ok: false,
error: error.message || "Something went wrong.",
});
};
api.use(errorHandler);

View File

@ -0,0 +1,7 @@
import express from "express";
import * as controllers from "../controllers/campaigns";
export const campaignsRouter = express.Router();
campaignsRouter.route("/").get(controllers.getMany);
campaignsRouter.route("/").post(controllers.create);

View File

@ -0,0 +1,6 @@
import express from "express";
import * as controllers from "../controllers/test";
export const testRouter = express.Router();
testRouter.route("/").get(controllers.getIndex);

7
backend/src/config.ts Normal file
View File

@ -0,0 +1,7 @@
import { SECRETS } from "./secrets";
export const CONFIG = {
API_PORT: 7231,
MONGODB_URI: SECRETS.MONGODB_URI,
MONGODB_DB_NAME: "osipad",
};

View File

@ -0,0 +1,19 @@
import mongoose from "mongoose";
interface ICampaign {
name: string;
contractAddress: string;
}
const campaignSchema = new mongoose.Schema<ICampaign>({
name: {
type: String,
required: true,
},
contractAddress: {
type: String,
required: true,
},
});
export const Campaign = mongoose.model<ICampaign>("Campaign", campaignSchema);

11
backend/src/db/index.ts Normal file
View File

@ -0,0 +1,11 @@
import mongoose from "mongoose";
import { CONFIG } from "../config";
export async function connectToDb() {
try {
await mongoose.connect(CONFIG.MONGODB_URI);
console.log("✅ Connected to MongoDB.");
} catch (error) {
console.error("❌ Couldn't connect to MongoDB.", error);
}
}

109
backend/tsconfig.json Normal file
View File

@ -0,0 +1,109 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}

View File

@ -2,5 +2,6 @@ rm ./frontend/src/evm-output/*
cp "./evm/ignition/deployments/chain-31337/deployed_addresses.json" "./frontend/src/evm-output/deployed_addresses.json"
cp "./evm/ignition/deployments/chain-31337/artifacts/MessageBoxModule#MessageBox.json" "./frontend/src/evm-output/MessageBox.artifacts.json"
cp "./evm/ignition/deployments/chain-31337/artifacts/MainModule#MessageBox.json" "./frontend/src/evm-output/MessageBox.artifacts.json"
cp "./evm/ignition/deployments/chain-31337/artifacts/MainModule#PADToken.json" "./frontend/src/evm-output/PADToken.artifacts.json"
cp "./evm/ignition/deployments/chain-31337/artifacts/MainModule#PADTokenStake.json" "./frontend/src/evm-output/PADTokenStake.artifacts.json"

View File

@ -4,16 +4,19 @@ pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
contract PADToken is ERC20, Ownable, ERC20Permit {
contract PADToken is ERC20, Ownable {
constructor(address initialOwner)
ERC20("PAD Token", "PAD")
Ownable(initialOwner)
ERC20Permit("PAD Token")
{}
function mint(address to, uint256 amount) public onlyOwner {
_mint(to, amount);
}
function approveMax(address spender) public returns (bool) {
uint value = type(uint256).max;
return approve(spender, value);
}
}

View File

@ -0,0 +1,98 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "./PADToken.sol";
contract PADTokenStake {
// pool id => pool info
mapping (uint => Pool) pools;
// staker => deposits
mapping(address => Deposit[]) deposits;
uint nextPoolId = 0;
uint nextDepositId = 0;
PADToken immutable padToken;
struct Pool {
uint id;
uint lockdownDays;
uint rewardPercentage;
}
struct Deposit {
uint id;
address staker;
uint poolId;
uint amount;
uint lockedAt;
uint releasedAt;
}
constructor(PADToken _padToken) {
padToken = _padToken;
_initPools();
}
function _initPools() internal {
pools[0] = Pool({
id: nextPoolId,
lockdownDays: 30,
rewardPercentage: 25
});
nextPoolId++;
pools[1] = Pool({
id: nextPoolId,
lockdownDays: 60,
rewardPercentage: 50
});
nextPoolId++;
}
function stake(uint poolId, uint amount) external {
Pool memory pool = pools[poolId];
Deposit memory newDeposit = Deposit({
id: nextDepositId,
staker: msg.sender,
poolId: poolId,
amount: amount,
lockedAt: block.timestamp,
releasedAt: block.timestamp + (pool.lockdownDays * 1 days)
});
deposits[msg.sender].push(newDeposit);
}
function getDeposit(uint depositId) public view returns (Deposit memory) {
Deposit memory deposit;
for (uint i = 0; i < deposits[msg.sender].length; i++) {
deposit = deposits[msg.sender][i];
if (deposit.id == depositId) {
return deposit;
}
}
revert("Deposit with the given ID not found.");
}
function getWithdrawPenalty(uint depositId) public view returns (uint) {
Deposit memory deposit = getDeposit(depositId);
uint remainingMs = deposit.releasedAt - block.timestamp;
if (remainingMs <= 0) {
return 0;
}
// TODO Find a meaningful formula
return 100;
}
function withdraw(uint depositId, bool acceptPenaltyCut) external {
uint penalty = getWithdrawPenalty(depositId);
if (penalty > 0) {
require(acceptPenaltyCut, "You should accept the penalty cut.");
}
Deposit memory deposit = getDeposit(depositId);
Pool memory pool = pools[deposit.poolId];
uint amountToTransfer = (deposit.amount * pool.rewardPercentage / 100) - penalty;
padToken.transfer(deposit.staker, amountToTransfer);
}
}

View File

@ -7,9 +7,13 @@ const MainModule = buildModule("MainModule", (m) => {
PAD_TOKEN_INITIAL_OWNER
);
const messageBox = m.contract("MessageBox", ["Hello OsiPad!"]); // TODO Remove
const padToken = m.contract("PADToken", [initialOwner]);
return { padToken };
const padTokenStake = m.contract("PADTokenStake", [padToken]);
return { messageBox, padToken, padTokenStake };
});
export default MainModule;

View File

@ -4,12 +4,15 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"dev": "vite --port 7232",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"@mdi/js": "^7.4.47",
"@mdi/react": "^1.6.1",
"@tanstack/react-query": "^5.37.1",
"@tanstack/react-router": "^1.28.7",
"react": "^18.2.0",
"react-dom": "^18.2.0",

View File

@ -5,6 +5,15 @@ settings:
excludeLinksFromLockfile: false
dependencies:
'@mdi/js':
specifier: ^7.4.47
version: 7.4.47
'@mdi/react':
specifier: ^1.6.1
version: 1.6.1
'@tanstack/react-query':
specifier: ^5.37.1
version: 5.37.1(react@18.2.0)
'@tanstack/react-router':
specifier: ^1.28.7
version: 1.28.7(react-dom@18.2.0)(react@18.2.0)
@ -729,6 +738,16 @@ packages:
'@jridgewell/sourcemap-codec': 1.4.15
dev: true
/@mdi/js@7.4.47:
resolution: {integrity: sha512-KPnNOtm5i2pMabqZxpUz7iQf+mfrYZyKCZ8QNz85czgEt7cuHcGorWfdzUMWYA0SD+a6Hn4FmJ+YhzzzjkTZrQ==}
dev: false
/@mdi/react@1.6.1:
resolution: {integrity: sha512-4qZeDcluDFGFTWkHs86VOlHkm6gnKaMql13/gpIcUQ8kzxHgpj31NuCkD8abECVfbULJ3shc7Yt4HJ6Wu6SN4w==}
dependencies:
prop-types: 15.8.1
dev: false
/@noble/curves@1.3.0:
resolution: {integrity: sha512-t01iSXPuN+Eqzb4eBX0S5oubSqXbK/xXa1Ne18Hj8f9pStxztHCE2gfboSp/dZRLSqfuLpRK2nDXDK+W9puocA==}
dependencies:
@ -920,6 +939,19 @@ packages:
engines: {node: '>=12'}
dev: false
/@tanstack/query-core@5.36.1:
resolution: {integrity: sha512-BteWYEPUcucEu3NBcDAgKuI4U25R9aPrHSP6YSf2NvaD2pSlIQTdqOfLRsxH9WdRYg7k0Uom35Uacb6nvbIMJg==}
dev: false
/@tanstack/react-query@5.37.1(react@18.2.0):
resolution: {integrity: sha512-EhtBNA8GL3XFeSx6VYUjXQ96n44xe3JGKZCzBINrCYlxbZP6UwBafv7ti4eSRWc2Fy+fybQre0w17gR6lMzULA==}
peerDependencies:
react: ^18.0.0
dependencies:
'@tanstack/query-core': 5.36.1
react: 18.2.0
dev: false
/@tanstack/react-router@1.28.7(react-dom@18.2.0)(react@18.2.0):
resolution: {integrity: sha512-eSOg/ffG8KJ9E3oAJnhiiQtz5dNM/7M5PL2BItZeAZF+0CSIGi0eI97orGDknY42iMdE+1KRkCKdfuutln2dxw==}
engines: {node: '>=12'}
@ -2275,7 +2307,6 @@ packages:
/object-assign@4.1.1:
resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}
engines: {node: '>=0.10.0'}
dev: true
/object-hash@3.0.0:
resolution: {integrity: sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==}
@ -2458,6 +2489,14 @@ packages:
hasBin: true
dev: true
/prop-types@15.8.1:
resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}
dependencies:
loose-envify: 1.4.0
object-assign: 4.1.1
react-is: 16.13.1
dev: false
/punycode@2.3.1:
resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
engines: {node: '>=6'}
@ -2477,6 +2516,10 @@ packages:
scheduler: 0.23.0
dev: false
/react-is@16.13.1:
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
dev: false
/react-refresh@0.14.0:
resolution: {integrity: sha512-wViHqhAd8OHeLS/IRMJjTSDHF3U9eWi62F/MledQGPdJGDhodXJ9PBLNGr6WWL7qlH12Mt3TyTpbS+hGXMjCzQ==}
engines: {node: '>=0.10.0'}

View File

@ -0,0 +1,59 @@
import { mdiAlertCircleOutline } from "@mdi/js";
import Icon from "@mdi/react";
import { useQuery } from "@tanstack/react-query";
import { fetchCampaigns } from "../query/fetchers/campaigns";
import { cn } from "../utils/style";
interface Props {
className?: string;
}
export function CampaignsGrid({ className }: Props) {
const campaignsQuery = useQuery({
queryKey: ["campaigns"],
queryFn: fetchCampaigns,
});
if (campaignsQuery.isPending) {
return (
<div className={className}>
<span className="loading loading-spinner loading-lg"></span>
</div>
);
}
if (campaignsQuery.isError) {
return (
<div className={cn("flex justify-center", className)}>
<div role="alert" className="alert alert-error w-auto">
<Icon path={mdiAlertCircleOutline} size={1} />
<span>Couldn't load campaigns.</span>
</div>
</div>
);
}
return (
<div
className={cn(
"grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",
className
)}
>
{campaignsQuery.data.map((campaign) => (
<div key={campaign._id} className="card bg-base-200">
<figure>
<img
src="https://img.daisyui.com/images/stock/photo-1606107557195-0e29a4b5b4aa.jpg"
alt="Shoes"
/>
</figure>
<div className="card-body items-start">
<h2 className="text-xl font-bold">{campaign.name}</h2>
<span>Lorem ipsum</span>
</div>
</div>
))}
</div>
);
}

View File

@ -0,0 +1,31 @@
import { Link } from "@tanstack/react-router";
import { ConnectMetamaskButton } from "./ConnectMetamaskButton";
export function Header() {
return (
<header className="bg-primary text-primary-content p-4 flex items-center">
<div className="flex-grow">
<span className="text-4xl font-bold">OsiPad&trade;</span>
<hr className="my-1" />
<div className="flex gap-3">
<Link to="/" className="[&.active]:font-bold">
Home
</Link>
<Link to="/about" className="[&.active]:font-bold">
About
</Link>
<Link to="/message-box" className="[&.active]:font-bold">
Message Box
</Link>
<Link to="/pad-token" className="[&.active]:font-bold">
PAD Token
</Link>
<Link to="/pad-token-stake" className="[&.active]:font-bold">
PAD Token Stake
</Link>
</div>
</div>
<ConnectMetamaskButton />
</header>
);
}

3
frontend/src/config.ts Normal file
View File

@ -0,0 +1,3 @@
export const CONFIG = {
API_BASE_URL: "http://localhost:7231",
};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,4 +1,5 @@
{
"MainModule#PADToken": "0x5FbDB2315678afecb367f032d93F642f64180aa3",
"MessageBoxModule#MessageBox": "0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512"
"MainModule#MessageBox": "0x7a2088a1bFc9d81c55368AE168C2C02570cB814F",
"MainModule#PADToken": "0x09635F643e140090A9A8Dcd712eD6285858ceBef",
"MainModule#PADTokenStake": "0xc5a5C42992dECbae36851359345FE25997F5C42d"
}

View File

@ -1,3 +1,4 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { RouterProvider, createRouter } from "@tanstack/react-router";
import React from "react";
import ReactDOM from "react-dom/client";
@ -5,6 +6,8 @@ import { ContextsProvider } from "./components/ContextsProvider";
import "./index.css";
import { routeTree } from "./routeTree.gen";
const queryClient = new QueryClient();
const router = createRouter({ routeTree });
declare module "@tanstack/react-router" {
interface Register {
@ -15,7 +18,9 @@ declare module "@tanstack/react-router" {
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<ContextsProvider>
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
</ContextsProvider>
</React.StrictMode>
);

View File

@ -0,0 +1,15 @@
import { CONFIG } from "../../config";
export const fetchCampaigns = async () => {
const resp = await fetch(`${CONFIG.API_BASE_URL}/campaigns`);
if (!resp.ok) {
throw new Error("Network error.");
}
const respBody = await resp.json();
if (!respBody.ok) {
throw new Error(respBody.message || "Something went wrong.");
}
return respBody.data;
};

View File

@ -16,6 +16,7 @@ import { Route as rootRoute } from './routes/__root'
// Create Virtual Routes
const PadTokenStakeLazyImport = createFileRoute('/pad-token-stake')()
const PadTokenLazyImport = createFileRoute('/pad-token')()
const MessageBoxLazyImport = createFileRoute('/message-box')()
const AboutLazyImport = createFileRoute('/about')()
@ -23,6 +24,13 @@ const IndexLazyImport = createFileRoute('/')()
// Create/Update Routes
const PadTokenStakeLazyRoute = PadTokenStakeLazyImport.update({
path: '/pad-token-stake',
getParentRoute: () => rootRoute,
} as any).lazy(() =>
import('./routes/pad-token-stake.lazy').then((d) => d.Route),
)
const PadTokenLazyRoute = PadTokenLazyImport.update({
path: '/pad-token',
getParentRoute: () => rootRoute,
@ -63,6 +71,10 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof PadTokenLazyImport
parentRoute: typeof rootRoute
}
'/pad-token-stake': {
preLoaderRoute: typeof PadTokenStakeLazyImport
parentRoute: typeof rootRoute
}
}
}
@ -73,6 +85,7 @@ export const routeTree = rootRoute.addChildren([
AboutLazyRoute,
MessageBoxLazyRoute,
PadTokenLazyRoute,
PadTokenStakeLazyRoute,
])
/* prettier-ignore-end */

View File

@ -1,6 +1,6 @@
import { createRootRoute, Link, Outlet } from "@tanstack/react-router";
import { createRootRoute, Outlet } from "@tanstack/react-router";
import { Toaster } from "sonner";
import { ConnectMetamaskButton } from "../components/ConnectMetamaskButton";
import { Header } from "../components/Header";
export const Route = createRootRoute({
component: RootLayout,
@ -9,27 +9,7 @@ export const Route = createRootRoute({
function RootLayout() {
return (
<>
<header className="bg-primary text-primary-content p-4 flex items-center">
<div className="flex-grow">
<span className="text-4xl font-bold">OsiPad&trade;</span>
<hr className="my-1" />
<div className="flex gap-3">
<Link to="/" className="[&.active]:font-bold">
Home
</Link>
<Link to="/about" className="[&.active]:font-bold">
About
</Link>
<Link to="/message-box" className="[&.active]:font-bold">
Message Box
</Link>
<Link to="/pad-token" className="[&.active]:font-bold">
PAD Token
</Link>
</div>
</div>
<ConnectMetamaskButton />
</header>
<Header />
<main>
<Outlet />
<Toaster />

View File

@ -1,4 +1,5 @@
import { createLazyFileRoute } from "@tanstack/react-router";
import { CampaignsGrid } from "../components/CampaignsGrid";
export const Route = createLazyFileRoute("/")({
component: IndexPage,
@ -14,12 +15,14 @@ function IndexPage() {
</h2>
</div>
<p>
<p className="mb-8">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci
nesciunt ipsa possimus sed? Maxime eos iusto facere natus commodi
consectetur ad pariatur minima quisquam. Soluta esse minus porro nemo
at.
</p>
<CampaignsGrid />
</div>
);
}

View File

@ -0,0 +1,74 @@
import { createLazyFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { useStore } from "../store";
import { toastError, tryWithToast } from "../utils/toast";
import { formatPadTokenAmount } from "../utils/ui";
import { padToken, padTokenStake } from "../web3";
export const Route = createLazyFileRoute("/pad-token-stake")({
component: PadTokenStakePage,
});
function PadTokenStakePage() {
const connectedAccount = useStore((state) => state.connectedAccount);
const [allowance, setAllowance] = useState("(nothingness)");
const getAllowanceAmount = async () => {
if (!connectedAccount) {
toastError("Get Current Allowance", "Connect your wallet first.");
return;
}
await tryWithToast("Get Current Allowance", async () => {
const owner = connectedAccount;
const spender = padTokenStake.options.address;
const allowance: bigint = await padToken.methods
.allowance(owner, spender)
.call();
setAllowance(formatPadTokenAmount(allowance));
});
};
const approveMax = async () => {
if (!connectedAccount) {
toastError("Approve Max", "Connect your wallet first.");
return;
}
await tryWithToast("Approve Max", async () => {
const owner = connectedAccount;
const spender = padTokenStake.options.address;
await padToken.methods.approveMax(spender).send({ from: owner });
});
};
return (
<div className="container mx-auto p-4 grid lg:grid-cols-2 xl:grid-cols-3 gap-4">
<div className="card bg-base-200">
<div className="card-body items-start">
<h2 className="text-2xl font-bold">Allowance</h2>
<div>
<span className="font-bold">
Allowance of PADTokenStake contract, for my PAD tokens:
</span>{" "}
{allowance}
</div>
<button
type="button"
className="btn btn-primary"
onClick={() => getAllowanceAmount()}
>
Get
</button>
<button
type="button"
className="btn btn-primary"
onClick={() => approveMax()}
>
Approve Max
</button>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,5 @@
export const cn = (
...args: Array<undefined | null | boolean | string>
): string => {
return args.filter((arg) => typeof arg === "string").join(" ");
};

View File

@ -5,5 +5,8 @@ export function shortenAddress(address: string) {
}
export function formatPadTokenAmount(amount: bigint) {
if (Number(amount) === Math.pow(2, 256)) {
return "∞ PAD";
}
return `${web3.utils.fromWei(amount, "ether").replace(/\.*$/, "")} PAD`;
}

View File

@ -1,6 +1,7 @@
import { Web3 } from "web3";
import messageBoxArtifacts from "./evm-output/MessageBox.artifacts.json";
import padTokenArtifacts from "./evm-output/PADToken.artifacts.json";
import padTokenStakeArtifacts from "./evm-output/PADTokenStake.artifacts.json";
import deployedAddresses from "./evm-output/deployed_addresses.json";
export let web3: Web3;
@ -16,10 +17,15 @@ if (window.ethereum) {
export const messageBox = new web3!.eth.Contract(
messageBoxArtifacts.abi,
deployedAddresses["MessageBoxModule#MessageBox"]
deployedAddresses["MainModule#MessageBox"]
);
export const padToken = new web3!.eth.Contract(
padTokenArtifacts.abi,
deployedAddresses["MainModule#PADToken"]
);
export const padTokenStake = new web3!.eth.Contract(
padTokenStakeArtifacts.abi,
deployedAddresses["MainModule#PADTokenStake"]
);