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

feat: viem wrapper with readContract and base methods #25

Merged
merged 4 commits into from
Jul 19, 2024
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
32 changes: 0 additions & 32 deletions apps/api/src/api.controller.spec.ts

This file was deleted.

14 changes: 0 additions & 14 deletions apps/api/src/api.controller.ts

This file was deleted.

6 changes: 2 additions & 4 deletions apps/api/src/api.module.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { MiddlewareConsumer, Module, NestModule } from "@nestjs/common";
import { ProvidersModule } from "@packages/providers";

import { ApiController } from "./api.controller";
import { RequestLoggerMiddleware } from "./common/middleware/request.middleware";
import { MetricsController } from "./metrics/metrics.controller";

Expand All @@ -10,8 +8,8 @@ import { MetricsController } from "./metrics/metrics.controller";
* Here we import all required modules and register the controllers for the ZKchainHub API.
*/
@Module({
imports: [ProvidersModule],
controllers: [ApiController, MetricsController],
imports: [],
controllers: [MetricsController],
providers: [],
})
export class ApiModule implements NestModule {
Expand Down
22 changes: 0 additions & 22 deletions apps/api/test/app.e2e-spec.ts

This file was deleted.

24 changes: 0 additions & 24 deletions libs/providers/src/evmProvider.service.spec.ts

This file was deleted.

15 changes: 0 additions & 15 deletions libs/providers/src/evmProvider.service.ts

This file was deleted.

1 change: 1 addition & 0 deletions libs/providers/src/exceptions/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./invalidArgument.exception";
6 changes: 6 additions & 0 deletions libs/providers/src/exceptions/invalidArgument.exception.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export class InvalidArgumentException extends Error {
constructor(message: string) {
super(message);
this.name = "InvalidArgumentException";
}
}
2 changes: 1 addition & 1 deletion libs/providers/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from "./providers";
export * from "./providers.module";
export * from "./evmProvider.service";
2 changes: 1 addition & 1 deletion libs/providers/src/providers.module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Module } from "@nestjs/common";

import { EvmProviderService } from "./evmProvider.service";
import { EvmProviderService } from "./providers";

/**
* Module for managing provider services.
Expand Down
150 changes: 150 additions & 0 deletions libs/providers/src/providers/evmProvider.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import { createMock } from "@golevelup/ts-jest";
import { Test, TestingModule } from "@nestjs/testing";
import { parseAbi } from "abitype";
import * as viem from "viem";
import { localhost } from "viem/chains";

import { EvmProviderService } from "./evmProvider.service";

const mockClient = createMock<ReturnType<typeof viem.createPublicClient>>();

jest.mock("viem", () => ({
...jest.requireActual("viem"),
createPublicClient: jest.fn().mockImplementation(() => mockClient),
http: jest.fn(),
}));

describe("EvmProviderService", () => {
let viemProvider: EvmProviderService;
const testAbi = parseAbi([
"function balanceOf(address owner) view returns (uint256)",
"function tokenURI(uint256 tokenId) pure returns (string)",
]);

beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
providers: [
{
provide: EvmProviderService,
useFactory: () => {
const rpcUrl = "http://localhost:8545";
const chain = localhost;
return new EvmProviderService(rpcUrl, chain);
},
},
],
}).compile();

viemProvider = app.get<EvmProviderService>(EvmProviderService);
});

afterEach(() => {
jest.clearAllMocks();
});

describe("getBalance", () => {
it("should return the balance of the specified address", async () => {
const address = "0x123456789";
const expectedBalance = 100n;
jest.spyOn(mockClient, "getBalance").mockResolvedValue(expectedBalance);

const balance = await viemProvider.getBalance(address);

expect(balance).toBe(expectedBalance);
expect(mockClient.getBalance).toHaveBeenCalledWith({ address });
});
});

describe("getBlockNumber", () => {
it("should return the current block number", async () => {
const expectedBlockNumber = 1000n;
jest.spyOn(mockClient, "getBlockNumber").mockResolvedValue(expectedBlockNumber);

const blockNumber = await viemProvider.getBlockNumber();

expect(blockNumber).toBe(expectedBlockNumber);
});
});

describe("getGasPrice", () => {
it("should return the current gas price", async () => {
const expectedGasPrice = BigInt(100);

// Mock the getGasPrice method of the Viem client
jest.spyOn(viemProvider["client"], "getGasPrice").mockResolvedValue(expectedGasPrice);

const gasPrice = await viemProvider.getGasPrice();

expect(gasPrice).toBe(expectedGasPrice);
});
});

describe("getStorageAt", () => {
it("should return the value of the storage slot at the given address and slot number", async () => {
const address = "0x123456789";
const slot = 1;
const expectedValue = "0xabcdef";
jest.spyOn(mockClient, "getStorageAt").mockResolvedValue(expectedValue);

const value = await viemProvider.getStorageAt(address, slot);

expect(value).toBe(expectedValue);
expect(mockClient.getStorageAt).toHaveBeenCalledWith({ address, slot: "0x1" });
});

it("should throw an error if the slot is not a positive integer", async () => {
const address = "0x123456789";
const slot = -1;

await expect(viemProvider.getStorageAt(address, slot)).rejects.toThrowError(
"Slot must be a positive integer number. Received: -1",
);
});
});

describe("readContract", () => {
it("should call the readContract method of the Viem client with the correct arguments", async () => {
const contractAddress = "0x123456789";
const abi = testAbi;
const functionName = "balanceOf";
const expectedReturnValue = 5n;

// Mock the readContract method of the Viem client
jest.spyOn(mockClient, "readContract").mockResolvedValue(expectedReturnValue);

const returnValue = await viemProvider.readContract(contractAddress, abi, functionName);

expect(returnValue).toBe(expectedReturnValue);
expect(mockClient.readContract).toHaveBeenCalledWith({
address: contractAddress,
abi,
functionName,
});
});

it("should call the readContract method of the Viem client with the correct arguments when args are provided", async () => {
const contractAddress = "0x123456789";
const functionName = "tokenURI";
const args = [1n] as const;
const expectedReturnValue = "tokenUri";

// Mock the readContract method of the Viem client
jest.spyOn(mockClient, "readContract").mockResolvedValue(expectedReturnValue);

const returnValue = await viemProvider.readContract(
contractAddress,
testAbi,
functionName,
args,
);

expect(returnValue).toBe(expectedReturnValue);
expect(mockClient.readContract).toHaveBeenCalledWith({
address: contractAddress,
abi: testAbi,
functionName,
args,
});
});
});
});
Loading