Skip to content

Commit

Permalink
Update show and withdraw logic
Browse files Browse the repository at this point in the history
  • Loading branch information
weiqiushi committed Jan 3, 2024
1 parent c660737 commit 01072a1
Show file tree
Hide file tree
Showing 7 changed files with 172 additions and 100 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ node_modules

# solidity-coverage files
/abi/
/testDatas/
2 changes: 1 addition & 1 deletion contracts/fake_nft_contract.sol
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ pragma solidity ^0.8.0;

import "./public_data_storage.sol";

contract FakeNFTContract is IERCPublicDataContract, IERC721VerfiyDataHash {
contract FakeNFTContract is IERCPublicDataContract, IERC721VerifyDataHash {
mapping (uint256 => bytes32) public tokenDataHashes;
mapping (bytes32 => address) public dataOwners;

Expand Down
194 changes: 107 additions & 87 deletions contracts/public_data_storage.sol

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion scripts/ERCMerkleTree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ export enum HashType {
export function calcHash(buf: Uint8Array, type: HashType): Uint8Array {
let ret = type == HashType.Sha256 ? ethers.sha256(buf) : ethers.keccak256(buf);

// 取低16bytes
return ethers.getBytes(ret);
}

Expand Down
16 changes: 14 additions & 2 deletions scripts/deploy.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
import { ethers, network } from "hardhat";
import { ethers, network, upgrades } from "hardhat";
import * as fs from "node:fs";
import { Exchange } from "../typechain-types";

async function main() {
const dmcContract = await (await ethers.deployContract("DMCToken", [ethers.parseEther("100000000")])).waitForDeployment();
let dmcAddress = await dmcContract.getAddress();
console.log("DMCToken deployed to:", dmcAddress);
const gwtContract = await (await ethers.deployContract("GWTToken", [dmcAddress])).waitForDeployment();
const gwtContract = await (await ethers.deployContract("GWTToken")).waitForDeployment();

let gwtAddress = await gwtContract.getAddress();
console.log("GWT deployed to:", gwtAddress);

let exchange = await (await upgrades.deployProxy(await ethers.getContractFactory("Exchange"),
[dmcAddress, gwtAddress],
{
initializer: "initialize",
kind: "uups",
timeout: 0
})).waitForDeployment() as unknown as Exchange;

let listLibrary = await (await ethers.getContractFactory("SortedScoreList")).deploy();
let proofLibrary = await (await ethers.getContractFactory("PublicDataProof")).deploy();
Expand All @@ -23,12 +32,15 @@ async function main() {
let publicDataStorageAddress = await publicDataStorage.getAddress();
console.log("PublicDataStorage deployed to:", publicDataStorageAddress);

await (await gwtContract.enableMinter([await exchange.getAddress()])).wait();

await(await gwtContract.enableTransfer([publicDataStorageAddress])).wait();

if (network.name !== "hardhat") {
fs.writeFileSync(`${network.name}-deployed.json`, JSON.stringify({
DMCToken: dmcAddress,
GWTToken: gwtAddress,
exchange: await exchange.getAddress(),
PublicDataStore: publicDataStorageAddress
}));
}
Expand Down
13 changes: 13 additions & 0 deletions scripts/generate_proof.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,19 @@ import fs from "node:fs"
import { MerkleTree } from "./ERCMerkleTree";
import { compareBytes } from "./ERCMerkleTreeUtil";

export async function genProofByIndex(filepath: string, index: number, treeStorePath: string): Promise<[number, Uint8Array[], Uint8Array, Uint8Array]> {
let tree = MerkleTree.load(JSON.parse(fs.readFileSync(treeStorePath, {encoding: 'utf-8'})));
let file_op = fs.openSync(filepath, "r");

let buf = new Uint8Array(1024);
buf.fill(0);

fs.readSync(file_op, buf, {position: index * 1024});
let path = tree.getPath(index);

return [index, path, buf, tree.proofByPath(path, index, buf)];
}

export async function generateProof(filepath: string, nonce_block_height: number, treeStorePath: string): Promise<[number, Uint8Array[], Uint8Array, Uint8Array]> {
let tree = MerkleTree.load(JSON.parse(fs.readFileSync(treeStorePath, {encoding: 'utf-8'})));

Expand Down
45 changes: 36 additions & 9 deletions test/test_public_data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,28 @@ describe("PublicDataStorage", function () {
await (await gwtToken.connect(signers[16]).approve(await contract.getAddress(), ethers.parseEther("210000000"))).wait();
});

it("set sys config", async () => {
let config = await contract.sysConfig();
let setConfig: PublicDataStorage.SysConfigStruct = {
minDepositRatio: config.minDepositRatio,
minPublicDataStorageWeeks: config.minPublicDataStorageWeeks,
minLockWeeks: config.minLockWeeks,
blocksPerCycle: config.blocksPerCycle,
topRewards: config.topRewards,
lockAfterShow: config.lockAfterShow,
showTimeout: config.showTimeout,
maxNonceBlockDistance: config.maxNonceBlockDistance,
minRankingScore: config.minRankingScore,
minDataSize: config.minDataSize
};
setConfig.showTimeout = 720n;
setConfig.minRankingScore = 1n;
await (await contract.setSysConfig(setConfig)).wait();

expect((await contract.sysConfig()).showTimeout).to.equal(720);
})


it("create public data", async () => {
// 需要的最小抵押:1/8 GB * 96(周) * 64(倍) = 768 GWT
await expect(contract.createPublicData(TestDatas[0].hash, 64, ethers.parseEther("768"), ethers.ZeroAddress, 0))
Expand Down Expand Up @@ -229,7 +251,7 @@ describe("PublicDataStorage", function () {
let [tx, nonce_block] = await showData(signers[2]);
await expect(tx).emit(contract, "SupplierBalanceChanged").withArgs(signers[2].address, ethers.parseEther("9808"), ethers.parseEther("192"));

await mine(await contract.sysConfigShowTimeout());
await mine((await contract.sysConfig()).showTimeout);


// signers[2]得到奖励, 奖励从data[0]的余额里扣除
Expand All @@ -242,8 +264,12 @@ describe("PublicDataStorage", function () {
});

it("show data again", async() => {
let [tx] = await showData(signers[3]);
let [tx, nonce] = await showData(signers[3]);
await expect(tx).emit(contract, "SupplierBalanceChanged").withArgs(signers[3].address, ethers.parseEther("9808"), ethers.parseEther("192"));

// 要提现后,cycle数据才更新
await mine((await contract.sysConfig()).showTimeout);
await contract.connect(signers[3]).withdrawShow(TestDatas[0].hash, nonce);
expect(await contract.getCurrectLastShowed(TestDatas[0].hash)).have.ordered.members([signers[2].address, signers[3].address]);
});

Expand All @@ -252,30 +278,31 @@ describe("PublicDataStorage", function () {
for (let i = 4; i < 8; i++){
await (expect(contract.connect(signers[i]).pledgeGwt(ethers.parseEther("10000"))))
.emit(contract, "SupplierBalanceChanged").withArgs(signers[i].address, ethers.parseEther("10000"), 0);

await mine(720);
await showData(signers[i]);
let [tx, nonce] = await showData(signers[i]);
await mine((await contract.sysConfig()).showTimeout);
await (await contract.connect(signers[i]).withdrawShow(TestDatas[0].hash, nonce));
}

expect(await contract.getCurrectLastShowed(TestDatas[0].hash)).have.ordered.members([signers[7].address, signers[3].address, signers[4].address, signers[5].address, signers[6].address]);
});

it("suppliers withdraw cycle reward", async () => {
await mine(await contract.blocksPerCycle());
await mine((await contract.sysConfig()).blocksPerCycle);

// 奖池数量:84527.2, 本期可分配:84527.2 * 0.8 = 67,621.76
// data[0]可分到67,621.76 * 240 / 1600 = 10,143.264
// owner获得10143.264*0.2=2028.6528
//let cycleInfo = await contract.getCycleInfo(1);
await expect(contract.connect(signers[0]).withdrawAward(1, TestDatas[0].hash))
let tx = contract.connect(signers[0]).withdrawAward(1, TestDatas[0].hash);
await expect(tx)
.changeTokenBalance(gwtToken, signers[0], ethers.parseEther("2028.6528"));
// sponser获得10143.264*0.5 = 5071.632
await expect(contract.connect(signers[1]).withdrawAward(1, TestDatas[0].hash))
await expect(tx)
.changeTokenBalance(gwtToken, signers[1], ethers.parseEther("5071.632"));

// signers3-7每人获得10143.264*0.3/5 = 608.59584
for (let index = 3; index <= 7; index++) {
await expect(contract.connect(signers[index]).withdrawAward(1, TestDatas[0].hash))
await expect(tx)
.changeTokenBalance(gwtToken, signers[index], ethers.parseEther("608.59584"));
}
});
Expand Down

0 comments on commit 01072a1

Please sign in to comment.