Skip to content

Commit

Permalink
Contribution to housing fund added to front-end
Browse files Browse the repository at this point in the history
  • Loading branch information
ndkazu committed Apr 20, 2024
1 parent 2e949a1 commit 5e07f97
Show file tree
Hide file tree
Showing 10 changed files with 193 additions and 39 deletions.
12 changes: 4 additions & 8 deletions fs-dapp_2.0/src/components/pages/Council.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,9 @@ import { Toast } from 'flowbite-react';
import { NotificationTwoTone, WarningTwoTone } from '@ant-design/icons';
import {BN,formatBalance} from '@polkadot/util';

import { toUnit } from '../shared/utils';
import RolesApp from '../shared/modal';
import Referendum from '../shared/referendum';
import { Card, Col, Space } from 'antd';
import Identicon from '@polkadot/react-identicon';
import InfiniteScroll from "react-infinite-scroll-component";
import { Avatar, Divider, List, Skeleton } from "antd";

import { Card} from 'antd';
import { List } from "antd";
import { Button } from 'antd';

export function arrangeText(val:string){
Expand Down Expand Up @@ -97,7 +93,7 @@ export default function Council() {
events.forEach(({ event: { method, section, data } }) => {
if (section.toString().includes('rolesModule')) {
let meth = method.toString() + '\n';
formatBalance.setDefaults({ decimals: 12, unit: 'FS' });
formatBalance.setDefaults({ decimals: 11, unit: 'USD' });
let payed = formatBalance(new BN(fees.partialFee.toString()),{ withSi: true, withZero: false });
setEvents(`${meth} =>Paid fees: ${payed} `);
setShowToast(true);
Expand Down
3 changes: 1 addition & 2 deletions fs-dapp_2.0/src/components/pages/Dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { useAccountContext } from '../../contexts/Account_Context';
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js';
import { Pie } from 'react-chartjs-2';
import {BN,formatBalance} from '@polkadot/util';
import { toUnit } from '../shared/utils';
import { NavLink } from 'react-router-dom';
import { all } from 'axios';
ChartJS.register(ArcElement, Tooltip, Legend);
Expand Down Expand Up @@ -133,7 +132,7 @@ export default function Dashboard() {
<div>
<h1 className="text-3xl text-slate-700 font-bold">DASHBOARD</h1>
<p className="text-xl font-bold">
House Fund: {!treasury_balance ? '0' :formatBalance(treasury_balance,{ decimals:12, withUnit:'FS',withSi: true, withZero: false })}
House Fund: {!treasury_balance ? '0' :formatBalance(treasury_balance,{ decimals:11, withUnit:'USD',withSi: true, withZero: false })}
</p>
<p className="text-xl font-bold">Total Number of Users: {total_users_nbr}</p>
</div>
Expand Down
31 changes: 17 additions & 14 deletions fs-dapp_2.0/src/components/pages/Investor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ import React, { useEffect,useState } from 'react';
import { useAppContext } from '../../contexts/AppContext';
import { arrangeText } from './Council';
import { InvestorData } from '@/src/contexts/types';
import {BN,formatBalance} from '@polkadot/util';
import { Card, Button } from 'antd';
import {BN} from '@polkadot/util';
import { toUnit } from '../shared/utils';
import { Card } from 'antd';
import FundContribution from '../shared/contributionForm';

const data0:InvestorData={name:"",address:"",balance:"",fund_share:"",available_funds:"", reserved_funds:"", invested_funds:""}
const inv_image = "../../../INVESTOR.png"
Expand All @@ -20,11 +22,11 @@ const[idata,setIdatas] = useState<InvestorData>();

useEffect(()=>{
if (!api||!selectedAccount) return;
dispatch0({ type: 'SET_INVESTOR', payload: data0 });
let address0=selectedAccount.address;
api.query.system.account(address0, ({ data: free }: { data: { free: BN } }) => {
formatBalance.setDefaults({ decimals: 12, unit: 'FS' });
const free0 = formatBalance(free.free,{ withSi: true, withZero: false });
dispatch0({ type: 'SET_BALANCE', payload: free0 });
const free1 = toUnit(free.free.toString(),11)
dispatch0({ type: 'SET_BALANCE', payload: free1 });


});
Expand All @@ -34,15 +36,14 @@ useEffect(()=>{
let txt = data0.infos
let infos = arrangeText(txt);
let datas0:InvestorData={...data0,name:infos[0],address:selectedAccount.address,balance:balance,fund_share:data0.share};

dispatch0({ type: 'SET_INVESTOR', payload: datas0 });
api.query.housingFundModule.contributions(address0,(data:any)=>{
let data0 = data.toHuman();
if (data0){
formatBalance.setDefaults({ decimals: 12, unit: 'FS' });

let available_funds=formatBalance(new BN(data0.availableBalance.toString().split(',').join('')),{ withSi: true, withZero: false });
let reserved_funds=formatBalance(new BN(data0.reservedBalance.toString().split(',').join('')),{ withSi: true, withZero: false });
let invested_funds=formatBalance(new BN(data0.contributedBalance.toString().split(',').join('')),{ withSi: true, withZero: false });
console.log(data0);
if (data0){
let available_funds=toUnit(data0.availableBalance.toString().split(',').join(''),11);
let reserved_funds=toUnit(data0.reservedBalance.toString().split(',').join(''),11);
let invested_funds=toUnit(data0.contributedBalance.toString().split(',').join(''),11);

let datas:InvestorData={...datas0,available_funds,reserved_funds,invested_funds};
setIdatas(datas)
Expand All @@ -51,6 +52,7 @@ useEffect(()=>{
})
}
})


},[selectedAccount,blocks,api,dispatch0,balance])

Expand All @@ -77,8 +79,9 @@ const style1= { width: 450, height:400, background:`white`};
</Card>:"NO DATA"}
</p>

<p>
<Button>Contribute to fund</Button>
<p className=' p-10'>
<FundContribution/>

</p>

</div>
Expand Down
2 changes: 1 addition & 1 deletion fs-dapp_2.0/src/components/pages/Roles.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export default function Roles() {
});

api.query.system.account(address0, ({ data: free }: { data: { free: BN } }) => {
formatBalance.setDefaults({ decimals: 12, unit: 'FS' });
formatBalance.setDefaults({ decimals: 11, unit: 'USD' });
const free0 = formatBalance(free.free,{ withSi: true, withZero: false });

dispatch0({ type: 'SET_BALANCE', payload: free0 });
Expand Down
1 change: 0 additions & 1 deletion fs-dapp_2.0/src/components/shared/InfosForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { useAccountContext } from '../../contexts/Account_Context';
import { useAppContext } from '../../contexts/AppContext';
import { Button } from 'flowbite-react';


type Details = {
picture: string;
fullname: string;
Expand Down
152 changes: 152 additions & 0 deletions fs-dapp_2.0/src/components/shared/contributionForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import {useForm,FieldError} from 'react-hook-form';
import { useAccountContext } from '../../contexts/Account_Context';
import { useAppContext } from '../../contexts/AppContext';
import { toUnit } from './utils';
import { useState,useEffect } from 'react';
import {Checkbox } from 'antd';
import { Button } from 'flowbite-react';
import type { CheckboxProps } from 'antd';
import { NotificationTwoTone, WarningTwoTone } from '@ant-design/icons';
import { web3FromAddress } from '@polkadot/extension-dapp';
import { Toast } from 'flowbite-react';

type Contribution = {
amount: string;
}



export default function FundContribution(){

const {register,handleSubmit,formState:{errors}}= useForm<Contribution>();
const { api, selectedAccount} = useAppContext();
const [minc,setMinc]=useState(0);
const [contmin,setContmin]=useState(false);
const [event, setEvents] = useState('No Vote');
const [showToast, setShowToast] = useState(false);
const [warning, setWarning] = useState(false);



const onChange: CheckboxProps['onChange'] = (e) => {
console.log(`checked = ${e.target.checked}`);
setContmin(!contmin);
if (contmin===true){

}
};

function getEditorStyle(fieldError: FieldError|undefined){
return fieldError?'border-red-500':``;
}

const onSubmit= async(contribution:Contribution)=>{
if (!api||!selectedAccount) return;
let f_amount=0;
if(contmin===true){
f_amount=minc
}else{
f_amount= Number(contribution.amount)*1E11;
}
let who = selectedAccount.address;
const tx = await api.tx.housingFundModule.contributeToFund(f_amount);
const fees = await tx.paymentInfo(who);
const injector = await web3FromAddress(who);
tx.signAndSend(who, { signer: injector.signer }, ({ status, events, dispatchError }) => {
if (dispatchError && status.isInBlock) {
if (dispatchError.isModule) {
console.log(`Current status: ${status.type}`);
// for module errors, we have the section indexed, lookup
const decoded = api.registry.findMetaError(dispatchError.asModule);
const {name} = decoded;
setEvents(name.toString());
setShowToast(true);
setWarning(true);
}
} else if (status.isInBlock) {
events.forEach(({ event: { method, section, data } }) => {
if (section.toString().includes('housingFundModule')) {
let meth = method.toString() + '\n';

let payed = toUnit(fees.partialFee.toString(),11)
setEvents(`${meth} =>Paid fees: ${payed} `);
setShowToast(true);
setWarning(false);
}
});
} else {
}
});

}

function getMin(){
if (!api||!selectedAccount) return;
let res = Number(api.consts.housingFundModule.minContribution)
setMinc(res)
//formatBalance.setDefaults({ decimals: 11, unit: 'USD' });
//let min = formatBalance(new BN(res),{ withSi: true, withZero: false })
}

useEffect(()=>{
getMin();

},)


const fieldstyle = "flex flex-col mb-2"

return(
<div className="flex flex-col py-10 max-w-md mx-auto">
<h2 className="font-bold text-xl underline mb-3">Contribute To the Housing Fund</h2>
<Checkbox onChange={onChange} className=' text-xl font-bold'>Minimum ({toUnit(minc.toString(),11)})</Checkbox>
<p>
<form noValidate onSubmit={handleSubmit(onSubmit)}>
<div className={fieldstyle}>
<label htmlFor='amount'>Customised Contribution (In USD)</label>
<input style={!contmin?{backgroundColor: '#DAF7A6'}:{backgroundColor:'grey'}} defaultValue="5000" disabled={contmin} type='number' id='amount' className={getEditorStyle(errors.amount)}{...register('amount',{
min:{
value:5000,
message:'Amount below minimun'
}
})}/>
</div>
<div>
<Button
type="submit"
className="bg-blue-600 text-white font-bold text-xl"> CONTRIBUTE </Button>
</div>
</form>
</p>
<p>
{!(showToast === false) ? (
<Toast>
<div
className={
'shadow-md rounded-md flex text-white text-base items-center justify-normal ' +
(warning === true ? ' bg-red-500 animate-bounce ' : ' bg-green-600 animate-pulse')
}
>
<div>
{!(warning === true) ? (
<NotificationTwoTone twoToneColor="#52c41a" className="h-8 w-8" />
) : (
<WarningTwoTone twoToneColor="#eb2f96" className="h-8 w-8" />
)}
</div>
<div className="p-2">{event}</div>
<Toast.Toggle
onClick={() => {
setShowToast(false);
}}
/>
</div>
</Toast>
) : (
<div className=" p-2"> </div>
)}
</p>

</div>
)
}
2 changes: 1 addition & 1 deletion fs-dapp_2.0/src/components/shared/modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ const RolesApp: React.FC = () => {
events.forEach(({ event: { method, section, data } }) => {
if (section.toString().includes('rolesModule')) {
let meth = method.toString() + '\n';
formatBalance.setDefaults({ decimals: 12, unit: 'FS' });
formatBalance.setDefaults({ decimals: 11, unit: 'USD' });
let payed = formatBalance(new BN(fees.partialFee.toString()),{ withSi: true, withZero: false });
setEvents(`${meth} =>Paid fees: ${payed} `);
setShowToast(true);
Expand Down
12 changes: 0 additions & 12 deletions fs-dapp_2.0/src/components/shared/utils.ts

This file was deleted.

12 changes: 12 additions & 0 deletions fs-dapp_2.0/src/components/shared/utils.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
import {BN,formatBalance} from '@polkadot/util';

export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export function toUnit(balance: string, decimals: number) {
formatBalance.setDefaults({ decimals: 11, unit: 'USD' });
let value = formatBalance(new BN(balance),{ withSi: true, withZero: false })
return value
}
5 changes: 5 additions & 0 deletions pallets/housing_fund/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,14 @@ pub mod pallet {
pub trait Config: frame_system::Config + NFT::Config {
/// Because this pallet emits events, it depends on the runtime's definition of an event.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
#[pallet::constant]
type MinContribution: Get<BalanceOf<Self>>;

type FundThreshold: Get<BalanceOf<Self>>;

#[pallet::constant]
type MaxFundContribution: Get<BalanceOf<Self>>;

type MaxInvestorPerHouse: Get<u32>;
type PalletId: Get<PalletId>;

Expand Down

0 comments on commit 5e07f97

Please sign in to comment.