Skip to content

Commit

Permalink
Adapt backend and contract to use unix timestamp instead of index acc…
Browse files Browse the repository at this point in the history
…essors
  • Loading branch information
Pustalorc committed Aug 26, 2024
1 parent bccdaf3 commit 594cbfd
Show file tree
Hide file tree
Showing 9 changed files with 43 additions and 113 deletions.
2 changes: 1 addition & 1 deletion api/.env-sample
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
NETWORK_URL=http://63.33.55.29/?apikey=API_KEY
NETWORK_WALLET_PRIV_KEY=0x5b3244868464b97618e1545555f5ce5e443ad09dafb72c560a3d8018e1c2b2b3

CONTRACT_ADDRESS=0xBba1177A5aa4c1590173ee3E7034916752E66F45
CONTRACT_ADDRESS=0x4a661bE808177bBBc142934bCF70020fAD1Ca5e7
13 changes: 0 additions & 13 deletions api/contracts.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,19 +47,6 @@
{
"name": "HashStorage",
"abi": [
{
"inputs": [],
"name": "nextIndex",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "retrieve",
Expand Down
30 changes: 5 additions & 25 deletions api/docs/Endpoints.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
[Create new hashes for a set of tenants](#create-new-hashes-for-a-set-of-tenants)
[Get the latest hash stored for a tenant](#get-the-latest-hash-stored-for-a-tenant)
[Get the stored hash count for a tenant](#get-the-stored-hash-count-for-a-tenant)
[Get a specific hash by index for a tenant](#get-a-specific-hash-by-index-for-a-tenant)
[Get a specific hash by unix timestamp for a tenant](#get-a-specific-hash-by-unix-timestamp-for-a-tenant)

## Create new hashes for a set of tenants
Creates new hashes for all the tenants passed on the request body so they can be stored in blockchain.
Expand Down Expand Up @@ -70,36 +70,16 @@ None
}
```

## Get the stored hash count for a tenant
Retrieves the number of stored hashes for a specific tenant
## Get a specific hash by unix timestamp for a tenant
Retrieves a specific hash by the unix timestamp in all the stored hashes for a specific tenant
### Request Endpoint
GET `/countHashes/:tenantId`
GET `/getHash/:tenantId/:unixTimestamp`
### Request Body
None
### Success Result Example
```json
{
"message": "Retrieved the hash count for the tenant [email protected].", // A message explaining execution result
"result": "1" // The count of hashes stored for this tenant
}
```
### Error Example
```json
{
"message": "Tenant exampleTenant@exampleTable does not have a registered contract."
}
```

## Get a specific hash by index for a tenant
Retrieves a specific hash by the index in all the stored hashes for a specific tenant
### Request Endpoint
GET `/getHash/:tenantId/:index`
### Request Body
None
### Success Result Example
```json
{
"message": "Retrieved the hash at index 0 for the tenant [email protected].", // A message explaining execution result
"message": "Retrieved the hash with timestamp 1720648799999 for the tenant [email protected].", // A message explaining execution result
"result": {
"unixTimestamp": "1720648799999", // The unix timestamp for the stored hash
"storedHash": "2d57b6ad076fbc35d04e25e5493fc1f5559f75e05af3f712abe22948c9307281" // The stored hash
Expand Down
24 changes: 3 additions & 21 deletions api/docs/Hash API.postman_collection.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,37 +51,19 @@
"response": []
},
{
"name": "Get hash by index for a tenant",
"name": "Get hash by unix timestamp for a tenant",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "{{host}}/getHash/{{tenant-id}}/0",
"raw": "{{host}}/getHash/{{tenant-id}}/1720569600000",
"host": [
"{{host}}"
],
"path": [
"getHash",
"{{tenant-id}}",
"0"
]
}
},
"response": []
},
{
"name": "Get hash count for a tenant",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "{{host}}/countHashes/{{tenant-id}}",
"host": [
"{{host}}"
],
"path": [
"countHashes",
"{{tenant-id}}"
"1720569600000"
]
}
},
Expand Down
4 changes: 3 additions & 1 deletion api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
"start": "npx ts-node src/main.ts"
},
"dependencies": {
"@dotenvx/dotenvx": "^1.5.0",
"@dotenvx/dotenvx": "1.5.0",
"@types/cors": "2.8.17",
"@types/express": "4.17.21",
"@types/node": "20.12.11",
"cors": "2.8.5",
"eslint": "9.2.0",
"ethers": "6.13.2",
"express": "4.19.2",
Expand Down
25 changes: 10 additions & 15 deletions api/src/exposition/api/api.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import express, { Express, Request, Response } from "express";

import cors from "cors";

import { callContractMethodController, executeContractMethodController } from "../controllers/contract.controller";
import handleControllerCall from "../controllers";

import Logger from "../../helpers/logger.helper";
import Config from "../../types/Config.type";
import { apiKeyMiddleware } from "../middleware/apiKey.middleware";
import { createHashesController, getHashByIndexController, getHashController, getHashCountController } from "../controllers/factory.controller";
import { createHashesController, getHashByUnixTimestampController, getHashController } from "../controllers/factory.controller";

const app: Express = express();
app.use(cors({
origin: '*'
}))
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// app.use(apiKeyMiddleware);
Expand All @@ -35,25 +40,15 @@ app.get("/getHash/:tenantId", async (req: Request, res: Response) => {
await handleControllerCall(req, res, logger, getHashController);
});

app.get("/countHashes/:tenantId", async (req: Request, res: Response) => {
const tenantId: string = req.params.tenantId;
const requestMade: string = `GET /getHash/${tenantId}/count`;

logger.info(requestMade);
logger.debug(`${requestMade} ${JSON.stringify(req.headers)} ${JSON.stringify(req.query)} ${JSON.stringify(req.body)}`);

await handleControllerCall(req, res, logger, getHashCountController);
});

app.get("/getHash/:tenantId/:index", async (req: Request, res: Response) => {
app.get("/getHash/:tenantId/:unixTimestamp", async (req: Request, res: Response) => {
const tenantId: string = req.params.tenantId;
const index: string = req.params.index;
const requestMade: string = `GET /getHash/${tenantId}/${index}`;
const unixTimestamp: string = req.params.unixTimestamp;
const requestMade: string = `GET /getHash/${tenantId}/${unixTimestamp}`;

logger.info(requestMade);
logger.debug(`${requestMade} ${JSON.stringify(req.headers)} ${JSON.stringify(req.query)} ${JSON.stringify(req.body)}`);

await handleControllerCall(req, res, logger, getHashByIndexController);
await handleControllerCall(req, res, logger, getHashByUnixTimestampController);
});

app.get("/:contract/:address/:method", async (req: Request, res: Response) => {
Expand Down
46 changes: 15 additions & 31 deletions api/src/exposition/controllers/factory.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@ export async function createHashesController(req: Request): Promise<AppResult> {
const deployedContractsMethod: string = "deployedContracts";
const tenantContractName: string = "HashStorage";
const tenantStoreMethod: string = "store";

const data = req.body;
const date = data.dateTime || new Date().toISOString();
const date = data.dateTime ? new Date(data.dateTime) : new Date();
const unixTimestamp = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
const result: any = {
dateTime: date,
dateTime: data.dateTime,
timestamp: unixTimestamp,
addresses: {},
hashes: {}
};
Expand All @@ -50,7 +51,7 @@ export async function createHashesController(req: Request): Promise<AppResult> {

if (address != ZeroAddress) {
logger.debug("Calling contract to store.");
await executeContractMethod(tenantContractName, address, tenantStoreMethod, [{unixTimestamp: new Date(date).getTime(),storedHash: value}], {});
await executeContractMethod(tenantContractName, address, tenantStoreMethod, [{unixTimestamp: unixTimestamp, storedHash: value}], {});
result.hashes[key] = value;
}

Expand Down Expand Up @@ -91,9 +92,9 @@ export async function getHashController(req: Request): Promise<AppResult> {
}
}

export async function getHashByIndexController(req: Request): Promise<AppResult> {
export async function getHashByUnixTimestampController(req: Request): Promise<AppResult> {
const tenantId: string = req.params.tenantId;
const index: string = req.params.index;
const unixTimestamp: string = req.params.unixTimestamp;
const contractName: string = config.CONTRACT.NAME;
const contractAddress: string = config.CONTRACT.ADDRESS;
const methodName: string = "deployedContracts";
Expand All @@ -106,37 +107,20 @@ export async function getHashByIndexController(req: Request): Promise<AppResult>
throw new TenantContractNotFoundException(tenantId);
}

const result = await callContractMethod(tenantContractName, address, tenantContractMethod, [index], {});

return {
statusCode: 200,
body: {
message: `Retrieved the hash at index ${index} for the tenant ${tenantId}.`,
result
}
let date;
if (Number.isNaN(unixTimestamp)) {
date = new Date(unixTimestamp);
} else {
date = new Date(Number(unixTimestamp));
}
}

export async function getHashCountController(req: Request): Promise<AppResult> {
const tenantId: string = req.params.tenantId;
const contractName: string = config.CONTRACT.NAME;
const contractAddress: string = config.CONTRACT.ADDRESS;
const methodName: string = "deployedContracts";
const tenantContractName: string = "HashStorage";
const tenantContractMethod: string = "nextIndex";

let address = await callContractMethod(contractName, contractAddress, methodName, [tenantId], {});

if (address == ZeroAddress) {
throw new TenantContractNotFoundException(tenantId);
}

const result = await callContractMethod(tenantContractName, address, tenantContractMethod, [], {});
const unixTrimmed = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
const result = await callContractMethod(tenantContractName, address, tenantContractMethod, [unixTrimmed], {});

return {
statusCode: 200,
body: {
message: `Retrieved the hash count for the tenant ${tenantId}.`,
message: `Retrieved the hash with timestamp ${unixTimestamp} for the tenant ${tenantId}.`,
result
}
}
Expand Down
2 changes: 1 addition & 1 deletion hardhat/addresses-redB.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"HashStorageFactory":"0xBba1177A5aa4c1590173ee3E7034916752E66F45"}
{"HashStorageFactory":"0x4a661bE808177bBBc142934bCF70020fAD1Ca5e7"}
10 changes: 5 additions & 5 deletions hardhat/contracts/Alastria/Storage.sol
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@ struct Hash {

contract HashStorage {
mapping (uint256 => Hash) public storedHashes;
uint256 public nextIndex;
uint256 latestTimestamp;

function store(Hash calldata hashToStore) public {
storedHashes[nextIndex] = hashToStore;
nextIndex++;
storedHashes[hashToStore.unixTimestamp] = hashToStore;
latestTimestamp = hashToStore.unixTimestamp;
}

function retrieve() public view returns (Hash memory) {
require(nextIndex > 0, "No stored hashes");
return storedHashes[nextIndex - 1];
require(latestTimestamp > 0, "No stored hashes");
return storedHashes[latestTimestamp];
}
}

Expand Down

0 comments on commit 594cbfd

Please sign in to comment.