@huma-finance/widgets 0.0.47 → 0.0.48-beta.187

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@huma-finance/widgets",
3
- "version": "0.0.47",
3
+ "version": "0.0.48-beta.187+c2ad954",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -39,6 +39,8 @@
39
39
  "@mui/x-date-pickers": "^5.0.7",
40
40
  "@notifi-network/notifi-frontend-client": "^0.75.1",
41
41
  "@reduxjs/toolkit": "^1.8.6",
42
+ "@requestnetwork/payment-processor": "0.38.1-next.1918",
43
+ "@requestnetwork/request-client.js": "0.40.1-next.1918",
42
44
  "@types/utf8": "^3.0.1",
43
45
  "@walletconnect/ethereum-provider": "1.8.0",
44
46
  "@walletconnect/jsonrpc-http-connection": "^1.0.3",
@@ -119,6 +121,7 @@
119
121
  "@babel/preset-react": "^7.14.5",
120
122
  "@emotion/babel-plugin": "^11.10.2",
121
123
  "@emotion/babel-preset-css-prop": "^11.2.0",
124
+ "@requestnetwork/types": "^0.36.0",
122
125
  "@rollup/plugin-babel": "^6.0.3",
123
126
  "@rollup/plugin-commonjs": "^24.0.1",
124
127
  "@rollup/plugin-image": "^3.0.2",
@@ -192,5 +195,5 @@
192
195
  "optionalDependencies": {
193
196
  "encoding": "^0.1.13"
194
197
  },
195
- "gitHead": "af0cb55217eca44673d30a47eca96d11d9139906"
198
+ "gitHead": "c2ad954e101271a1f0d59dda4a4eaaf29c1336fc"
196
199
  }
@@ -0,0 +1,58 @@
1
+ import { useWeb3React } from '@web3-react/core'
2
+ import { PoolInfoType, toBigNumber } from '@huma-finance/shared'
3
+ import React, { useEffect } from 'react'
4
+
5
+ import useEA from '../../hooks/useEA'
6
+ import { LoadingModal } from '../LoadingModal'
7
+ import { WIDGET_STEP } from '../../store/widgets.store'
8
+ import { SignIn } from '../SignIn'
9
+
10
+ type Props = {
11
+ poolInfo: PoolInfoType
12
+ tokenId: string
13
+ }
14
+
15
+ export function Evaluation({ poolInfo, tokenId }: Props): React.ReactElement {
16
+ const {
17
+ checkingEA,
18
+ isWalletOwnershipVerificationRequired,
19
+ isWalletOwnershipVerified,
20
+ } = useEA()
21
+ const { account, chainId } = useWeb3React()
22
+
23
+ useEffect(() => {
24
+ if (account && chainId) {
25
+ checkingEA(
26
+ {
27
+ poolAddress: poolInfo.pool,
28
+ borrowerWalletAddress: account,
29
+ context: {
30
+ receivable: {
31
+ address: poolInfo.assetAddress!,
32
+ param: toBigNumber(tokenId).toHexString(),
33
+ },
34
+ },
35
+ },
36
+ WIDGET_STEP.ChooseAmount,
37
+ )
38
+ }
39
+ }, [
40
+ account,
41
+ chainId,
42
+ checkingEA,
43
+ poolInfo.assetAddress,
44
+ poolInfo.pool,
45
+ tokenId,
46
+ isWalletOwnershipVerified,
47
+ ])
48
+
49
+ if (isWalletOwnershipVerificationRequired) {
50
+ return <SignIn />
51
+ }
52
+ return (
53
+ <LoadingModal
54
+ title='Checking Invoice'
55
+ description='Checking if the invoice qualifies for factoring...'
56
+ />
57
+ )
58
+ }
@@ -0,0 +1,88 @@
1
+ import {
2
+ AccountStats,
3
+ PoolInfoType,
4
+ upScale,
5
+ useFeeManager,
6
+ } from '@huma-finance/shared'
7
+ import React, { useCallback, useState } from 'react'
8
+
9
+ import { useAppDispatch, useAppSelector } from '../../hooks/useRedux'
10
+ import { setBorrowInfo } from '../../store/widgets.reducers'
11
+ import { selectWidgetState } from '../../store/widgets.selectors'
12
+ import { WIDGET_STEP } from '../../store/widgets.store'
13
+ import { ChooseAmountModal } from '../ChooseAmountModal'
14
+
15
+ type Props = {
16
+ poolInfo: PoolInfoType
17
+ accountStats: AccountStats
18
+ }
19
+
20
+ export function ChooseAmount({
21
+ poolInfo,
22
+ accountStats,
23
+ }: Props): React.ReactElement | null {
24
+ const dispatch = useAppDispatch()
25
+ const { creditRecord } = accountStats
26
+ const [chargedFees, setChargedFees] = useState(0)
27
+ const [currentAmount, setCurrentAmount] = useState(0)
28
+ const { approval } = useAppSelector(selectWidgetState)
29
+ const { getFeesCharged } = useFeeManager(poolInfo.poolName, poolInfo.poolType)
30
+ const [remainder, setRemainder] = useState<string | number | undefined>(
31
+ approval!.receivable?.amountFormatted,
32
+ )
33
+
34
+ const getAvailableCreditLimit = () => {
35
+ if (approval && creditRecord) {
36
+ const principal = creditRecord.unbilledPrincipal
37
+ .add(creditRecord.totalDue)
38
+ .sub(creditRecord.feesAndInterestDue)
39
+ .toNumber()
40
+ return Number(approval.terms.creditLimitFormatted) - principal
41
+ }
42
+ return 0
43
+ }
44
+
45
+ const handleChangeAmount = useCallback(
46
+ (newAmount: number) => {
47
+ if (approval) {
48
+ setCurrentAmount(newAmount)
49
+ setChargedFees(getFeesCharged(newAmount))
50
+ setRemainder(Number(approval.receivable!.amountFormatted) - newAmount)
51
+ }
52
+ },
53
+ [approval, getFeesCharged],
54
+ )
55
+
56
+ const handleAction = useCallback(() => {
57
+ dispatch(
58
+ setBorrowInfo({
59
+ borrowAmount: currentAmount,
60
+ borrowAmountBN: upScale(currentAmount, approval?.token.decimal),
61
+ chargedFees,
62
+ remainder: Number(remainder!),
63
+ nextStep: WIDGET_STEP.ConfirmTransfer,
64
+ }),
65
+ )
66
+ }, [approval?.token.decimal, chargedFees, currentAmount, dispatch, remainder])
67
+
68
+ if (!approval) {
69
+ return null
70
+ }
71
+
72
+ return (
73
+ <ChooseAmountModal
74
+ title='Choose Amount'
75
+ description1='Access up to 80% of your invoice value'
76
+ description2='The remainder will be sent to your wallet when the invoice is paid'
77
+ sliderMax={getAvailableCreditLimit()}
78
+ currentAmount={currentAmount}
79
+ tokenSymbol={approval.token.symbol}
80
+ topLeft='Fees'
81
+ topRight={`${chargedFees} ${approval.token.symbol}`}
82
+ downLeft='Remainder'
83
+ downRight={`${remainder} ${approval.token.symbol}`}
84
+ handleChangeAmount={handleChangeAmount}
85
+ handleAction={handleAction}
86
+ />
87
+ )
88
+ }
@@ -0,0 +1,37 @@
1
+ import { isEmpty } from '@huma-finance/shared'
2
+ import React from 'react'
3
+
4
+ import { useAppDispatch, useAppSelector } from '../../hooks/useRedux'
5
+ import { setStep } from '../../store/widgets.reducers'
6
+ import { selectWidgetState } from '../../store/widgets.selectors'
7
+ import { WIDGET_STEP } from '../../store/widgets.store'
8
+ import { ConfirmTransferModal } from '../ConfirmTransferModal'
9
+
10
+ export function ConfirmTransfer(): React.ReactElement | null {
11
+ const dispatch = useAppDispatch()
12
+ const { borrowAmountNet, approval } = useAppSelector(selectWidgetState)
13
+
14
+ const handleAction = () => {
15
+ dispatch(setStep(WIDGET_STEP.ApproveNFT))
16
+ }
17
+
18
+ if (isEmpty(borrowAmountNet) || isEmpty(approval)) {
19
+ return null
20
+ }
21
+
22
+ return (
23
+ <ConfirmTransferModal
24
+ title='Confirm transaction details'
25
+ description={`Huma keeps your Invoice NFT as collateral until it's fully paid.`}
26
+ items={[
27
+ { leftText: 'Invoice NFT', rightText: 'Huma' },
28
+ {
29
+ leftText: `${borrowAmountNet!} ${approval?.token.symbol}`,
30
+ rightText: 'You',
31
+ },
32
+ ]}
33
+ actionText='APPROVE TRANSFER'
34
+ handleAction={handleAction}
35
+ />
36
+ )
37
+ }
@@ -0,0 +1,55 @@
1
+ import { useWeb3React } from '@web3-react/core'
2
+ import {
3
+ PoolInfoType,
4
+ sendTxAtom,
5
+ txAtom,
6
+ TxStateType,
7
+ useInvoiceNFTContract,
8
+ } from '@huma-finance/shared'
9
+ import { useAtom } from 'jotai'
10
+ import { useResetAtom } from 'jotai/utils'
11
+ import React, { useEffect } from 'react'
12
+
13
+ import { useAppDispatch } from '../../hooks/useRedux'
14
+ import { setStep } from '../../store/widgets.reducers'
15
+ import { WIDGET_STEP } from '../../store/widgets.store'
16
+ import { LoadingModal } from '../LoadingModal'
17
+ import { ViewOnExplorer } from '../ViewOnExplorer'
18
+
19
+ type Props = {
20
+ poolInfo: PoolInfoType
21
+ tokenId: string
22
+ }
23
+
24
+ export function ApproveNFT({ poolInfo, tokenId }: Props): React.ReactElement {
25
+ const dispatch = useAppDispatch()
26
+ const { provider } = useWeb3React()
27
+ const [{ state, txHash }, send] = useAtom(sendTxAtom)
28
+ const reset = useResetAtom(txAtom)
29
+ const invoiceNFTContract = useInvoiceNFTContract(poolInfo.poolName)
30
+
31
+ useEffect(() => {
32
+ if (state === TxStateType.Success) {
33
+ reset()
34
+ dispatch(setStep(WIDGET_STEP.Transfer))
35
+ }
36
+ }, [dispatch, reset, state])
37
+
38
+ useEffect(() => {
39
+ send({
40
+ contract: invoiceNFTContract!,
41
+ method: 'approve',
42
+ params: [poolInfo.pool, tokenId],
43
+ provider,
44
+ })
45
+ }, [invoiceNFTContract, poolInfo.pool, provider, send, tokenId])
46
+
47
+ return (
48
+ <LoadingModal
49
+ title='Approve Invoice Transfer'
50
+ description='Waiting for approval confirmation...'
51
+ >
52
+ <ViewOnExplorer txHash={txHash} />
53
+ </LoadingModal>
54
+ )
55
+ }
@@ -0,0 +1,34 @@
1
+ import { PoolInfoType, toBigNumber, upScale } from '@huma-finance/shared'
2
+ import React, { useCallback } from 'react'
3
+
4
+ import { useAppDispatch, useAppSelector } from '../../hooks/useRedux'
5
+ import { setStep } from '../../store/widgets.reducers'
6
+ import { selectWidgetState } from '../../store/widgets.selectors'
7
+ import { WIDGET_STEP } from '../../store/widgets.store'
8
+ import { TxSendModal } from '../TxSendModal'
9
+
10
+ type Props = {
11
+ poolInfo: PoolInfoType
12
+ tokenId: string
13
+ }
14
+
15
+ export function Transfer({ poolInfo, tokenId }: Props): React.ReactElement {
16
+ const dispatch = useAppDispatch()
17
+ const { decimals } = poolInfo.poolUnderlyingToken
18
+ const { borrowAmount } = useAppSelector(selectWidgetState)
19
+ const requestLoanBigNumber = toBigNumber(upScale(borrowAmount!, decimals))
20
+
21
+ const handleSuccess = useCallback(() => {
22
+ dispatch(setStep(WIDGET_STEP.Done))
23
+ }, [dispatch])
24
+
25
+ return (
26
+ <TxSendModal
27
+ poolInfo={poolInfo}
28
+ title='Transfer Invoice and Money'
29
+ method='drawdownWithReceivable'
30
+ params={[requestLoanBigNumber, poolInfo.assetAddress, tokenId]}
31
+ handleSuccess={handleSuccess}
32
+ />
33
+ )
34
+ }
@@ -0,0 +1,20 @@
1
+ import React from 'react'
2
+ import { useAppSelector } from '../../hooks/useRedux'
3
+ import { selectWidgetState } from '../../store/widgets.selectors'
4
+ import { TxDoneModal } from '../TxDoneModal'
5
+
6
+ type Props = {
7
+ handleAction: () => void
8
+ }
9
+
10
+ export function Success({ handleAction }: Props): React.ReactElement {
11
+ const { borrowAmountNet, remainder, approval } =
12
+ useAppSelector(selectWidgetState)
13
+
14
+ const content = [
15
+ `${borrowAmountNet} ${approval?.token.symbol} is now in your wallet.`,
16
+ `The remaining ${remainder} ${approval?.token.symbol} will be sent to your wallet when the invoice is paid.`,
17
+ ]
18
+
19
+ return <TxDoneModal handleAction={handleAction} content={content} />
20
+ }
@@ -0,0 +1,137 @@
1
+ import { useWeb3React } from '@web3-react/core'
2
+ import { RequestLogicTypes } from '@requestnetwork/types'
3
+ import {
4
+ POOL_NAME,
5
+ POOL_TYPE,
6
+ useAccountStats,
7
+ usePoolInfo,
8
+ } from '@huma-finance/shared'
9
+ import React, { useEffect, useState } from 'react'
10
+ import { useDispatch } from 'react-redux'
11
+ import { RequestNetwork } from '@requestnetwork/request-client.js'
12
+ import { getReceivableTokenIdForRequest } from '@requestnetwork/payment-processor'
13
+ import { BigNumberish } from 'ethers'
14
+
15
+ import { useAppSelector } from '../../hooks/useRedux'
16
+ import { setStep } from '../../store/widgets.reducers'
17
+ import { selectWidgetState } from '../../store/widgets.selectors'
18
+ import { WIDGET_STEP } from '../../store/widgets.store'
19
+ import { ErrorModal } from '../ErrorModal'
20
+ import { WidgetWrapper } from '../WidgetWrapper'
21
+ import { Evaluation } from './1-Evaluation'
22
+ import { ChooseAmount } from './2-ChooseAmount'
23
+ import { ConfirmTransfer } from './3-ConfirmTransfer'
24
+ import { ApproveNFT } from './4-ApproveNFT'
25
+ import { Transfer } from './5-Transfer'
26
+ import { Success } from './6-Success'
27
+
28
+ /**
29
+ * Invoice factoring pool borrow props
30
+ * @typedef {Object} RequestNetworkInvoiceFactoringBorrowProps
31
+ * @property {POOL_NAME} poolName The name of the pool.
32
+ * @property {POOL_TYPE} poolType The type of the pool.
33
+ * @property {string|BigNumber} tokenId The NFT token id representing invoice.
34
+ * @property {function():void} handleClose Function to notify to close the widget modal when user clicks the 'x' close button.
35
+ * @property {function((number|undefined)):void|undefined} handleSuccess Optional function to notify that the invoice pool borrow action is successful.
36
+ */
37
+ export interface RequestNetworkInvoiceFactoringBorrowProps {
38
+ poolName: keyof typeof POOL_NAME
39
+ poolType: keyof typeof POOL_TYPE
40
+ requestId: RequestLogicTypes.RequestId
41
+ handleClose: () => void
42
+ handleSuccess?: (blockNumber?: number) => void
43
+ }
44
+
45
+ export function RequestNetworkInvoiceFactoringBorrow({
46
+ poolName: poolNameStr,
47
+ poolType: poolTypeStr,
48
+ requestId,
49
+ handleClose,
50
+ handleSuccess,
51
+ }: RequestNetworkInvoiceFactoringBorrowProps): React.ReactElement | null {
52
+ const dispatch = useDispatch()
53
+ const { account, provider } = useWeb3React()
54
+ const poolName = POOL_NAME[poolNameStr]
55
+ const poolType = POOL_TYPE[poolTypeStr]
56
+ const poolInfo = usePoolInfo(poolName, poolType)
57
+ const { step, errorMessage } = useAppSelector(selectWidgetState)
58
+ const [accountStats] = useAccountStats(poolName, poolType, account)
59
+ const [tokenId, setTokenId] = useState<BigNumberish>()
60
+ const [isLoading, setIsLoading] = useState<boolean>(true)
61
+
62
+ useEffect(() => {
63
+ dispatch(setStep(WIDGET_STEP.Evaluation))
64
+ }, [dispatch])
65
+
66
+ useEffect(() => {
67
+ if (provider == null) {
68
+ return () => {} // Return empty func to satisty consistent return lint rule
69
+ }
70
+
71
+ // Refetch every 5 seconds until requestData is non-null
72
+ const interval = setInterval(() => {
73
+ async function getInvoice() {
74
+ if (provider == null) {
75
+ return
76
+ }
77
+
78
+ const requestNetwork = new RequestNetwork({
79
+ nodeConnectionConfig: {
80
+ baseURL: `https://xdai.gateway.request.network/`,
81
+ },
82
+ })
83
+ const request = await requestNetwork.fromRequestId(requestId)
84
+ const requestData = request.getData()
85
+ const tokenId = await getReceivableTokenIdForRequest(
86
+ requestData,
87
+ provider,
88
+ )
89
+
90
+ // Check if token ID exists yet for this request
91
+ if (tokenId) {
92
+ setTokenId(tokenId)
93
+ setIsLoading(false)
94
+ clearInterval(interval)
95
+ }
96
+ }
97
+ getInvoice()
98
+ }, 5000)
99
+
100
+ return () => clearInterval(interval)
101
+ }, [provider, requestId])
102
+
103
+ if (!poolInfo) {
104
+ return null
105
+ }
106
+
107
+ return (
108
+ <WidgetWrapper
109
+ isOpen
110
+ isLoading={isLoading}
111
+ handleClose={handleClose}
112
+ handleSuccess={handleSuccess}
113
+ >
114
+ {step === WIDGET_STEP.Evaluation && (
115
+ <Evaluation poolInfo={poolInfo} tokenId={tokenId!.toString()} />
116
+ )}
117
+ {step === WIDGET_STEP.ChooseAmount && (
118
+ <ChooseAmount poolInfo={poolInfo} accountStats={accountStats} />
119
+ )}
120
+ {step === WIDGET_STEP.ConfirmTransfer && <ConfirmTransfer />}
121
+ {step === WIDGET_STEP.ApproveNFT && (
122
+ <ApproveNFT poolInfo={poolInfo} tokenId={tokenId!.toString()} />
123
+ )}
124
+ {step === WIDGET_STEP.Transfer && (
125
+ <Transfer poolInfo={poolInfo} tokenId={tokenId!.toString()} />
126
+ )}
127
+ {step === WIDGET_STEP.Done && <Success handleAction={handleClose} />}
128
+ {step === WIDGET_STEP.Error && (
129
+ <ErrorModal
130
+ title='Invoice Factoring'
131
+ errorMessage={errorMessage}
132
+ handleOk={handleClose}
133
+ />
134
+ )}
135
+ </WidgetWrapper>
136
+ )
137
+ }
@@ -0,0 +1,65 @@
1
+ import { POOL_NAME, POOL_TYPE } from '@huma-finance/shared'
2
+ import { JsonRpcProvider } from '@ethersproject/providers'
3
+ import { Button } from '@mui/material'
4
+ import { Box } from '@mui/system'
5
+ import { useState } from 'react'
6
+ import { WalletWrapper } from './WalletWrapper'
7
+ import { initEnv } from './utils/env'
8
+ import { RequestNetworkInvoiceFactoringBorrowWidget } from '..'
9
+
10
+ initEnv()
11
+
12
+ function Fixture() {
13
+ const poolName = POOL_NAME.RequestNetwork
14
+ const poolType = POOL_TYPE.Invoice
15
+ const [showModal, setShowModal] = useState(false)
16
+ const [requestId, setRequestId] = useState(
17
+ '01a84260baadbf9a46ea205d485b1a773f863c7531d19b6dd1d5073d82a5c414b7',
18
+ )
19
+
20
+ const handleClick = () => {
21
+ setShowModal(true)
22
+ }
23
+
24
+ const handleClose = () => {
25
+ setShowModal(false)
26
+ }
27
+
28
+ return (
29
+ <>
30
+ <Box>Pool: {poolName}</Box>
31
+ <Box>Pool Type: {poolType}</Box>
32
+ <input
33
+ type='text'
34
+ value={requestId}
35
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
36
+ onChange={(event: any) => {
37
+ setRequestId(event.target.value)
38
+ }}
39
+ />
40
+ <Button variant='contained' onClick={handleClick}>
41
+ Borrow
42
+ </Button>
43
+ {showModal && (
44
+ <RequestNetworkInvoiceFactoringBorrowWidget
45
+ poolName={poolName}
46
+ poolType={poolType}
47
+ requestId={requestId}
48
+ handleClose={() => {
49
+ handleClose()
50
+ }}
51
+ handleSuccess={() => {
52
+ alert('Success')
53
+ }}
54
+ provider={new JsonRpcProvider()}
55
+ />
56
+ )}
57
+ </>
58
+ )
59
+ }
60
+
61
+ export default (
62
+ <WalletWrapper>
63
+ <Fixture />
64
+ </WalletWrapper>
65
+ )
package/src/index.tsx CHANGED
@@ -37,6 +37,10 @@ import { SuperfluidFactoring } from './components/SuperfluidFactoring'
37
37
  import { store } from './store'
38
38
  import { themeHuma } from './theme'
39
39
  import { WCProps } from './utilTypes'
40
+ import {
41
+ RequestNetworkInvoiceFactoringBorrow,
42
+ RequestNetworkInvoiceFactoringBorrowProps,
43
+ } from './components/RequestNetworkInvoiceFactoring'
40
44
 
41
45
  /**
42
46
  * Mapping of your JSON-RPC connections indexed by chainId
@@ -82,6 +86,31 @@ function Widget(props: WCProps<WidgetProps>) {
82
86
  )
83
87
  }
84
88
 
89
+ /**
90
+ * Invoice factoring pool borrow widget props
91
+ * @typedef {Object} RequestNetworkInvoiceFactoringBorrowWidgetProps
92
+ * @property {RequestNetworkInvoiceFactoringBorrowProps} RequestNetworkInvoiceFactoringBorrowProps - Invoice factoring pool borrow props.
93
+ * @property {WidgetProps} WidgetProps - Widget general props.
94
+ */
95
+ type RequestNetworkInvoiceFactoringBorrowWidgetProps =
96
+ RequestNetworkInvoiceFactoringBorrowProps & WidgetProps
97
+
98
+ /**
99
+ * Invoice factoring borrow widget
100
+ *
101
+ * @param {RequestNetworkInvoiceFactoringBorrowWidgetProps} props - The invoice factoring pool borrow widget props.
102
+ * @returns Invoice factoring pool borrow widget component
103
+ */
104
+ export function RequestNetworkInvoiceFactoringBorrowWidget(
105
+ props: RequestNetworkInvoiceFactoringBorrowWidgetProps,
106
+ ) {
107
+ return (
108
+ <Widget {...props}>
109
+ <RequestNetworkInvoiceFactoringBorrow {...props} />
110
+ </Widget>
111
+ )
112
+ }
113
+
85
114
  /**
86
115
  * Invoice factoring pool borrow widget props
87
116
  * @typedef {Object} InvoiceFactoringBorrowWidgetProps