Skip to content
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,4 @@ yarn-debug.log*
yarn-error.log*
.vscode/
.editorconfig
logs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { NumberFormatValues } from "react-number-format";

import { toSmartContractDecimals } from "@taikai/dappkit/dist/src/utils/numbers";
import { fireEvent } from "@testing-library/dom";
import BigNumber from "bignumber.js";

import CreateBountyTokenAmount, {
ZeroNumberFormatValues,
} from "components/bounty/create-bounty/token-amount/controller";

import { Network } from "interfaces/network";
import { DistributionsProps } from "interfaces/proposal";
import { Token } from "interfaces/token";

import { render } from "__tests__/utils/custom-render";

jest.mock("x-hooks/use-bepro", () => () => ({}));

const mockCurrentToken: Token = {
address: "0x1234567890123456789012345678901234567890",
name: "Mock Token",
symbol: "MOCK",
};

const mockCurrentNetwork: Network = {
id: 1,
name: "Mock Network",
updatedAt: new Date(),
createdAt: new Date(),
description: "Mock Description",
networkAddress: "0x1234567890123456789012345678901234567890",
creatorAddress: "0x1234567890123456789012345678901234567890",
openBounties: 0,
totalBounties: 0,
allowCustomTokens: false,
councilMembers: [],
banned_domains: [],
closeTaskAllowList: [],
allow_list: [],
mergeCreatorFeeShare: 0.05,
proposerFeeShare: 0.5,
chain: {
chainId: 1,
chainRpc: "https://mock-rpc.com",
name: "Mock Chain",
chainName: "Mock Chain",
chainShortName: "MOCK",
chainCurrencySymbol: "MOCK",
chainCurrencyDecimals: "18",
chainCurrencyName: "Mock Token",
blockScanner: "https://mock-scanner.com",
registryAddress: "0x1234567890123456789012345678901234567890",
eventsApi: "https://mock-events.com",
isDefault: true,
closeFeePercentage: 10,
cancelFeePercentage: 1.0,
networkCreationFeePercentage: 0.5,
},
};

describe("TokenAmountController", () => {
beforeEach(() => {
jest.clearAllMocks();
});

it("fuzzes total input and ensures internal adjusted total is divisible by 100 in contract units", () => {
let executions = 0;

let issueAmount = ZeroNumberFormatValues;
let previewAmount = ZeroNumberFormatValues;

const setPreviewAmount = jest.fn((value: NumberFormatValues) => {
previewAmount = value;
});
const updateIssueAmount = jest.fn((value: NumberFormatValues) => {
issueAmount = value;
});

while (executions < 100) {
const decimals = Math.floor(Math.random() * 13) + 6;
const randomValue = parseFloat((Math.random() * 499999 + 1).toFixed(decimals));

const result = render(<CreateBountyTokenAmount
currentToken={mockCurrentToken}
updateCurrentToken={jest.fn()}
addToken={jest.fn()}
canAddCustomToken={true}
defaultToken={mockCurrentToken}
userAddress="0x1234567890123456789012345678901234567890"
customTokens={[]}
tokenBalance={new BigNumber(1)}
issueAmount={issueAmount}
updateIssueAmount={updateIssueAmount}
isFunders={true}
decimals={decimals}
isFunding={false}
needValueValidation={false}
previewAmount={previewAmount}
distributions={{} as DistributionsProps}
currentNetwork={mockCurrentNetwork}
setPreviewAmount={setPreviewAmount}
setDistributions={jest.fn()}
sethasAmountError={jest.fn()}
/>);

const totalAmountInput = result.getAllByTestId("total-amount-input")[0];

const valueString = randomValue.toString();

fireEvent.change(totalAmountInput, { target: { value: valueString } });

result.rerender(<CreateBountyTokenAmount
currentToken={mockCurrentToken}
updateCurrentToken={jest.fn()}
addToken={jest.fn()}
canAddCustomToken={true}
defaultToken={mockCurrentToken}
userAddress="0x1234567890123456789012345678901234567890"
customTokens={[]}
tokenBalance={new BigNumber(1)}
issueAmount={issueAmount}
updateIssueAmount={updateIssueAmount}
isFunders={true}
decimals={decimals}
isFunding={false}
needValueValidation={false}
previewAmount={previewAmount}
distributions={{} as DistributionsProps}
currentNetwork={mockCurrentNetwork}
setPreviewAmount={setPreviewAmount}
setDistributions={jest.fn()}
sethasAmountError={jest.fn()}
/>);

const newValueContract = toSmartContractDecimals(issueAmount.value, decimals);

expect(Number(BigInt(newValueContract) % BigInt(100))).toBe(0);

jest.clearAllMocks();
result.unmount();

executions += 1;
}
});
});
38 changes: 27 additions & 11 deletions components/bounty/create-bounty/token-amount/controller.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {useEffect, useState} from "react";
import {NumberFormatValues} from "react-number-format";

import { fromSmartContractDecimals, toSmartContractDecimals } from "@taikai/dappkit/dist/src/utils/numbers";
import BigNumber from "bignumber.js";
import {useDebouncedCallback} from "use-debounce";

Expand All @@ -14,7 +15,7 @@ import {useUserStore} from "x-hooks/stores/user/user.store";

import CreateBountyTokenAmountView from "./view";

const ZeroNumberFormatValues = {
export const ZeroNumberFormatValues = {
value: "",
formattedValue: "",
floatValue: 0,
Expand Down Expand Up @@ -101,8 +102,8 @@ export default function CreateBountyTokenAmount({
}

const handleNumberFormat = (v: BigNumber) => ({
value: v.decimalPlaces(5, 0).toFixed(),
floatValue: v.toNumber(),
value: v.decimalPlaces(Math.min(10, decimals), 0).toFixed(),
floatValue: +v.decimalPlaces(Math.min(10, decimals), 0).toFixed(),
formattedValue: v.decimalPlaces(Math.min(10, decimals), 0).toFixed()
});

Expand Down Expand Up @@ -139,15 +140,22 @@ export default function CreateBountyTokenAmount({
return;
}

const amountOfType =
let totalAmount =
BigNumber(type === "reward"
? _calculateTotalAmountFromGivenReward(value)
: value);

const contractTotalAmount = +toSmartContractDecimals(totalAmount.toString(), decimals);

if (contractTotalAmount % 100 !== 0) {
const adjustedContractTotalAmount = Math.ceil(contractTotalAmount / 100) * 100;
totalAmount = BigNumber(fromSmartContractDecimals(adjustedContractTotalAmount, decimals));
}

const initialDistributions = calculateDistributedAmounts( chain.closeFeePercentage,
mergeCreatorFeeShare,
proposerFeeShare,
amountOfType,
totalAmount,
[
{
recipient: currentUser?.walletAddress,
Expand All @@ -166,24 +174,32 @@ export default function CreateBountyTokenAmount({
const _distributions = { totalServiceFees, ...initialDistributions}

if(type === 'reward'){
const total = BigNumber(_calculateTotalAmountFromGivenReward(value));
updateIssueAmount(handleNumberFormat(total))
if (amountIsGtBalance(total.toNumber(), tokenBalance) && !isFunding) {
updateIssueAmount(handleNumberFormat(totalAmount))
const rewardValue = BigNumber(calculateRewardAmountGivenTotalAmount(totalAmount.toNumber()));

if (rewardValue !== value) {
setPreviewAmount(handleNumberFormat(rewardValue));
}

if (amountIsGtBalance(totalAmount.toNumber(), tokenBalance) && !isFunding) {
setInputError("bounty:errors.exceeds-allowance");
sethasAmountError(true);
}
}

if(type === 'total'){
const rewardValue = BigNumber(calculateRewardAmountGivenTotalAmount(value));
const rewardValue = BigNumber(calculateRewardAmountGivenTotalAmount(totalAmount.toNumber()));
setPreviewAmount(handleNumberFormat(rewardValue));

if (totalAmount.toFixed() !== value.toString()) {
updateIssueAmount(handleNumberFormat(totalAmount));
}

if (rewardValue.isLessThan(BigNumber(currentToken?.minimum))) {
setInputError("bounty:errors.exceeds-minimum-amount");
sethasAmountError(true);
}
}

setDistributions(_distributions);
}

Expand Down Expand Up @@ -223,8 +239,8 @@ export default function CreateBountyTokenAmount({
setInputError("");
sethasAmountError(false);
}
debouncedDistributionsUpdater(values.value, type);
setType(handleNumberFormat(BigNumber(values.value)));
debouncedDistributionsUpdater(values.value, type);
}
}

Expand Down
6 changes: 5 additions & 1 deletion components/pages/task/create-task/controller.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,11 @@ export default function CreateTaskPage({
function handleUpdateToken(e: Token, type: 'transactional' | 'reward') {
const ERC20 = type === 'transactional' ? transactionalERC20 : rewardERC20
const setToken = type === 'transactional' ? setTransactionalToken : setRewardToken
setToken(e)
setToken(e);
setIssueAmount(ZeroNumberFormatValues);
setRewardAmount(ZeroNumberFormatValues);
setPreviewAmount(ZeroNumberFormatValues);
setDistributions(undefined);
ERC20.setAddress(e.address)
}

Expand Down
1 change: 1 addition & 0 deletions helpers/analytic-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ export const analyticEvents: AnalyticEvents = {
create_task_approve_amount: [analytic("ga4")],
create_pre_task: [analytic("ga4")],
created_task: [analytic("ga4")],
user_logged_in: [analytic("ga4")],
}
6 changes: 3 additions & 3 deletions scripts/deploy-multichain.js
Original file line number Diff line number Diff line change
Expand Up @@ -260,9 +260,9 @@ async function main(option = 0) {
isDefault: false,
color: "#29b6af",
lockAmountForNetworkCreation: DEPLOY_LOCK_AMOUNT_FOR_NETWORK_CREATION,
networkCreationFeePercentage: DEPLOY_LOCK_FEE_PERCENTAGE || DEFAULT_LOCK_FEE_PERCENTAGE / DIVISOR,
closeFeePercentage: DEPLOY_CLOSE_BOUNTY_FEE || DEFAULT_LOCK_FEE_PERCENTAGE / DIVISOR,
cancelFeePercentage: DEPLOY_CANCEL_BOUNTY_FEE || DEFAULT_LOCK_FEE_PERCENTAGE / DIVISOR,
networkCreationFeePercentage: (+DEPLOY_LOCK_FEE_PERCENTAGE || DEFAULT_LOCK_FEE_PERCENTAGE) / DIVISOR,
closeFeePercentage: (+DEPLOY_CLOSE_BOUNTY_FEE || DEFAULT_CLOSE_BOUNTY_FEE) / DIVISOR,
cancelFeePercentage: (+DEPLOY_CANCEL_BOUNTY_FEE || DEFAULT_CANCEL_BOUNTY_FEE) / DIVISOR,
icon: "QmZ8dSeJp9pZn2TFy2gp7McfMj9HapqnPW3mwnnrDLKtZs",
}
});
Expand Down