hardhat init

This commit is contained in:
emochka2007 2024-05-08 00:28:55 +03:00
parent d3c421471e
commit 5d5443b8ac
51 changed files with 17331 additions and 33376 deletions

25
chain-api/.eslintrc.js Normal file
View File

@ -0,0 +1,25 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};

View File

@ -15,3 +15,5 @@ node_modules
# Hardhat Ignition default folder for deployments against a local node # Hardhat Ignition default folder for deployments against a local node
ignition/deployments/chain-31337 ignition/deployments/chain-31337
dist

4
chain-api/.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

73
chain-api/README.md Normal file
View File

@ -0,0 +1,73 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Installation
```bash
$ npm install
```
## Running the app
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Test
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).

View File

@ -0,0 +1,22 @@
require('@nomicfoundation/hardhat-toolbox');
require('@nomicfoundation/hardhat-ethers');
const dotenv = require('dotenv');
dotenv.config();
const config = {
solidity: '0.8.24',
networks: {
amoy: {
url: `https://polygon-amoy.g.alchemy.com/v2/pEtFFy_Qr_NrM1vMnlzSXmYXkozVNzLy`,
accounts: [process.env.POLYGON_PK || ''],
},
},
paths: {
sources: './src/hardhat/contracts',
// tests: './src/hardhat/test',
cache: './src/hardhat/cache',
artifacts: './src/hardhat/artifacts',
},
};
module.exports = config;

8
chain-api/nest-cli.json Normal file
View File

@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

16648
chain-api/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

77
chain-api/package.json Normal file
View File

@ -0,0 +1,77 @@
{
"name": "accounter-api",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@chainlink/contracts": "^1.1.0",
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/mapped-types": "*",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/swagger": "^7.3.1",
"@nomicfoundation/hardhat-toolbox": "^5.0.0",
"dotenv": "^16.4.5",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.1"
},
"devDependencies": {
"@nestjs/cli": "^10.0.0",
"@nestjs/schematics": "^10.0.0",
"@nestjs/testing": "^10.0.0",
"@nomicfoundation/hardhat-ethers": "^3.0.5",
"@types/express": "^4.17.17",
"@types/jest": "^29.5.2",
"@types/node": "^20.3.1",
"@types/supertest": "^2.0.12",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"eslint": "^8.42.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.0",
"ethers": "^6.12.1",
"hardhat": "^2.22.3",
"jest": "^29.5.0",
"prettier": "^3.0.0",
"source-map-support": "^0.5.21",
"supertest": "^6.3.3",
"ts-jest": "^29.1.0",
"ts-loader": "^9.4.3",
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.1.3"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

View File

@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

View File

@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}

View File

@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ContractFactoryModule } from './contract-factory/contract-factory.module';
import { ContractInteractModule } from './contract-interact/contract-interact.module';
@Module({
imports: [ContractFactoryModule, ContractInteractModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

View File

@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View File

@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ContractFactoryController } from './contract-factory.controller';
import { ContractFactoryService } from './contract-factory.service';
describe('ContractFactoryController', () => {
let controller: ContractFactoryController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ContractFactoryController],
providers: [ContractFactoryService],
}).compile();
controller = module.get<ContractFactoryController>(ContractFactoryController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,25 @@
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
} from '@nestjs/common';
import { ContractFactoryService } from './contract-factory.service';
import { CreateContractFactoryDto } from './dto/create-contract-factory.dto';
import { UpdateContractFactoryDto } from './dto/update-contract-factory.dto';
import { ApiTags } from '@nestjs/swagger';
@ApiTags('contract-factory')
@Controller('contract-factory')
export class ContractFactoryController {
constructor(
private readonly contractFactoryService: ContractFactoryService,
) {}
@Post('')
create(@Body() createContractFactoryDto: CreateContractFactoryDto) {
return this.contractFactoryService.create(createContractFactoryDto);
}
}

View File

@ -0,0 +1,11 @@
import { HardhatModule } from '../hardhat/module/hardhat.module';
import { Module } from '@nestjs/common';
import { ContractFactoryService } from './contract-factory.service';
import { ContractFactoryController } from './contract-factory.controller';
@Module({
imports: [HardhatModule],
controllers: [ContractFactoryController],
providers: [ContractFactoryService],
})
export class ContractFactoryModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ContractFactoryService } from './contract-factory.service';
describe('ContractFactoryService', () => {
let service: ContractFactoryService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ContractFactoryService],
}).compile();
service = module.get<ContractFactoryService>(ContractFactoryService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,11 @@
import { HardhatService } from '../hardhat/module/hardhat.service';
import { Injectable } from '@nestjs/common';
import { CreateContractFactoryDto } from './dto/create-contract-factory.dto';
@Injectable()
export class ContractFactoryService {
constructor(private readonly hhService: HardhatService) {}
async create(createContractFactoryDto: CreateContractFactoryDto) {
return await this.hhService.deploySalaryContract();
}
}

View File

@ -0,0 +1,12 @@
import { ApiProperty } from '@nestjs/swagger';
export enum ContractType {
SALARY,
AGREEMENT,
}
export class CreateContractFactoryDto {
@ApiProperty({
enum: ContractType,
})
contractType: ContractType;
}

View File

@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateContractFactoryDto } from './create-contract-factory.dto';
export class UpdateContractFactoryDto extends PartialType(CreateContractFactoryDto) {}

View File

@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ContractInteractController } from './contract-interact.controller';
import { ContractInteractService } from './contract-interact.service';
describe('ContractInteractController', () => {
let controller: ContractInteractController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ContractInteractController],
providers: [ContractInteractService],
}).compile();
controller = module.get<ContractInteractController>(ContractInteractController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,49 @@
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
} from '@nestjs/common';
import { ContractInteractService } from './contract-interact.service';
import { CreateContractInteractDto } from './dto/create-contract-interact.dto';
import { UpdateContractInteractDto } from './dto/update-contract-interact.dto';
import { ApiTags } from '@nestjs/swagger';
@ApiTags('contract-interact')
@Controller('contract-interact')
export class ContractInteractController {
constructor(
private readonly contractInteractService: ContractInteractService,
) {}
@Post()
create(@Body() createContractInteractDto: CreateContractInteractDto) {
return this.contractInteractService.create(createContractInteractDto);
}
@Get()
findAll() {
return this.contractInteractService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.contractInteractService.findOne(+id);
}
@Patch(':id')
update(
@Param('id') id: string,
@Body() updateContractInteractDto: UpdateContractInteractDto,
) {
return this.contractInteractService.update(+id, updateContractInteractDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.contractInteractService.remove(+id);
}
}

View File

@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { ContractInteractService } from './contract-interact.service';
import { ContractInteractController } from './contract-interact.controller';
@Module({
controllers: [ContractInteractController],
providers: [ContractInteractService],
})
export class ContractInteractModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ContractInteractService } from './contract-interact.service';
describe('ContractInteractService', () => {
let service: ContractInteractService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ContractInteractService],
}).compile();
service = module.get<ContractInteractService>(ContractInteractService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,26 @@
import { Injectable } from '@nestjs/common';
import { CreateContractInteractDto } from './dto/create-contract-interact.dto';
import { UpdateContractInteractDto } from './dto/update-contract-interact.dto';
@Injectable()
export class ContractInteractService {
create(createContractInteractDto: CreateContractInteractDto) {
return 'This action adds a new contractInteract';
}
findAll() {
return `This action returns all contractInteract`;
}
findOne(id: number) {
return `This action returns a #${id} contractInteract`;
}
update(id: number, updateContractInteractDto: UpdateContractInteractDto) {
return `This action updates a #${id} contractInteract`;
}
remove(id: number) {
return `This action removes a #${id} contractInteract`;
}
}

View File

@ -0,0 +1,8 @@
import { ApiProperty } from '@nestjs/swagger';
export class CreateContractInteractDto {
@ApiProperty()
contractAddress: string;
@ApiProperty()
sender: string;
}

View File

@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreateContractInteractDto } from './create-contract-interact.dto';
export class UpdateContractInteractDto extends PartialType(CreateContractInteractDto) {}

18
chain-api/src/hardhat/.gitignore vendored Normal file
View File

@ -0,0 +1,18 @@
node_modules
.env
# Hardhat files
/cache
/artifacts
# TypeChain files
/typechain
/typechain-types
# solidity-coverage files
/coverage
/coverage.json
# Hardhat Ignition default folder for deployments against a local node
ignition/deployments/chain-31337
ignition/deployments/chain-80002

View File

@ -0,0 +1,34 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";
contract Salaries {
AggregatorV3Interface internal dataFeed;
/**
* Network: Sepolia
* Aggregator: BTC/USD
* Address: 0x1b44F3514812d835EB1BDB0acB33d3fA3351Ee43
*/
constructor() {
dataFeed = AggregatorV3Interface(
0xF0d50568e3A7e8259E16663972b11910F89BD8e7
);
}
/**
* Returns the latest answer.
*/
function getChainlinkDataFeedLatestAnswer() public view returns (int) {
// prettier-ignore
(
/* uint80 roundID */,
int answer,
/*uint startedAt*/,
/*uint timeStamp*/,
/*uint80 answeredInRound*/
) = dataFeed.latestRoundData();
return answer;
}
}

View File

@ -0,0 +1,11 @@
import { buildModule } from "@nomicfoundation/hardhat-ignition/modules";
//npx hardhat ignition deploy ignition/modules/Salaries.ts --network amoy
//SalariesModule#Salaries - 0xac45e95Dd5C7F9B1a6C3e4883d04952B9C974b05
const SalariesModule = buildModule("SalariesModule", (m) => {
const salaryContract = m.contract("Salaries");
const answer = m.call(salaryContract, "getChainlinkDataFeedLatestAnswer", []);
console.log("🚀 ~ SalariesModule ~ answer:", answer);
return { salaryContract };
});
export default SalariesModule;

View File

@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { HardhatService } from './hardhat.service';
@Module({
imports: [],
controllers: [],
providers: [HardhatService],
exports: [HardhatService],
})
export class HardhatModule {}

View File

@ -0,0 +1,31 @@
const hre = require('hardhat');
// import hre from 'hardhat';
import { Injectable } from '@nestjs/common';
@Injectable()
export class HardhatService {
async deploySalaryContract() {
// const { salaryAmount, userAddress } = req.body;
// // Read the Solidity contract template file
// const solidityCode = readSolidityTemplate(); // Implement this function to read the Solidity template file
// // Replace placeholders in the Solidity contract template with provided values
// const finalSolidityCode = replacePlaceholders(solidityCode, {
// salaryAmount,
// userAddress,
// });
// // Compile the Solidity contract
// const compiledContract = await compileSolidity(finalSolidityCode);
// // Deploy the contract
// const deployedContract = await deployContract(compiledContract);
const salaryC = await hre.ethers.getContractFactory('Salaries');
const myContract = await salaryC.deploy();
console.log(
'🚀 ~ HardhatService ~ deploySalaryContract ~ myContract:',
myContract,
);
}
}

17
chain-api/src/main.ts Normal file
View File

@ -0,0 +1,17 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('Chain')
.setDescription('The chain API description')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
await app.listen(3000);
console.log('Swagger avaliable at http://localhost:3000/api');
}
bootstrap();

View File

@ -0,0 +1,24 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});

View File

@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

View File

@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

21
chain-api/tsconfig.json Normal file
View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
}
}

View File

@ -1,15 +0,0 @@
import { HardhatUserConfig, vars } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";
import dotenv from "dotenv";
dotenv.config();
const config: HardhatUserConfig = {
solidity: "0.8.24",
networks: {
polygon: {
url: `https://polygon-amoy.g.alchemy.com/v2/pEtFFy_Qr_NrM1vMnlzSXmYXkozVNzLy`,
accounts: [process.env.POLYGON_PK || ""],
},
},
};
export default config;

View File

@ -1,4 +0,0 @@
{
"_format": "hh-sol-dbg-1",
"buildInfo": "../build-info/61afe259f874fc3da9eb2666746c2273.json"
}

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,3 +0,0 @@
{
"MultiSigWallet#MultiSigWallet": "0x375A5bbF574Cd10EaDCd9B632369Ce3644AcaE15"
}

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -1,15 +0,0 @@
{
"devDependencies": {
"@nomicfoundation/hardhat-toolbox": "^5.0.0",
"@types/chai": "^4.3.14",
"@types/mocha": "^10.0.6",
"@types/node": "^20.12.8",
"chai": "^4.4.1",
"hardhat": "^2.22.3",
"ts-node": "^10.9.2",
"typescript": "^5.4.5"
},
"dependencies": {
"dotenv": "^16.4.5"
}
}

View File

@ -1,127 +0,0 @@
import {
time,
loadFixture,
} from "@nomicfoundation/hardhat-toolbox/network-helpers";
import { anyValue } from "@nomicfoundation/hardhat-chai-matchers/withArgs";
import { expect } from "chai";
import hre from "hardhat";
describe("Lock", function () {
// We define a fixture to reuse the same setup in every test.
// We use loadFixture to run this setup once, snapshot that state,
// and reset Hardhat Network to that snapshot in every test.
async function deployOneYearLockFixture() {
const ONE_YEAR_IN_SECS = 365 * 24 * 60 * 60;
const ONE_GWEI = 1_000_000_000;
const lockedAmount = ONE_GWEI;
const unlockTime = (await time.latest()) + ONE_YEAR_IN_SECS;
// Contracts are deployed using the first signer/account by default
const [owner, otherAccount] = await hre.ethers.getSigners();
const Lock = await hre.ethers.getContractFactory("Lock");
const lock = await Lock.deploy(unlockTime, { value: lockedAmount });
return { lock, unlockTime, lockedAmount, owner, otherAccount };
}
describe("Deployment", function () {
it("Should set the right unlockTime", async function () {
const { lock, unlockTime } = await loadFixture(deployOneYearLockFixture);
expect(await lock.unlockTime()).to.equal(unlockTime);
});
it("Should set the right owner", async function () {
const { lock, owner } = await loadFixture(deployOneYearLockFixture);
expect(await lock.owner()).to.equal(owner.address);
});
it("Should receive and store the funds to lock", async function () {
const { lock, lockedAmount } = await loadFixture(
deployOneYearLockFixture
);
expect(await hre.ethers.provider.getBalance(lock.target)).to.equal(
lockedAmount
);
});
it("Should fail if the unlockTime is not in the future", async function () {
// We don't use the fixture here because we want a different deployment
const latestTime = await time.latest();
const Lock = await hre.ethers.getContractFactory("Lock");
await expect(Lock.deploy(latestTime, { value: 1 })).to.be.revertedWith(
"Unlock time should be in the future"
);
});
});
describe("Withdrawals", function () {
describe("Validations", function () {
it("Should revert with the right error if called too soon", async function () {
const { lock } = await loadFixture(deployOneYearLockFixture);
await expect(lock.withdraw()).to.be.revertedWith(
"You can't withdraw yet"
);
});
it("Should revert with the right error if called from another account", async function () {
const { lock, unlockTime, otherAccount } = await loadFixture(
deployOneYearLockFixture
);
// We can increase the time in Hardhat Network
await time.increaseTo(unlockTime);
// We use lock.connect() to send a transaction from another account
await expect(lock.connect(otherAccount).withdraw()).to.be.revertedWith(
"You aren't the owner"
);
});
it("Shouldn't fail if the unlockTime has arrived and the owner calls it", async function () {
const { lock, unlockTime } = await loadFixture(
deployOneYearLockFixture
);
// Transactions are sent using the first signer by default
await time.increaseTo(unlockTime);
await expect(lock.withdraw()).not.to.be.reverted;
});
});
describe("Events", function () {
it("Should emit an event on withdrawals", async function () {
const { lock, unlockTime, lockedAmount } = await loadFixture(
deployOneYearLockFixture
);
await time.increaseTo(unlockTime);
await expect(lock.withdraw())
.to.emit(lock, "Withdrawal")
.withArgs(lockedAmount, anyValue); // We accept any value as `when` arg
});
});
describe("Transfers", function () {
it("Should transfer the funds to the owner", async function () {
const { lock, unlockTime, lockedAmount, owner } = await loadFixture(
deployOneYearLockFixture
);
await time.increaseTo(unlockTime);
await expect(lock.withdraw()).to.changeEtherBalances(
[owner, lock],
[lockedAmount, -lockedAmount]
);
});
});
});
});

View File

@ -1,11 +0,0 @@
{
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"resolveJsonModule": true
}
}

4
docs.md Normal file
View File

@ -0,0 +1,4 @@
# links
chainlink-feeds amoy
https://docs.chain.link/data-feeds/price-feeds/addresses?network=polygon&page=1