@huma-finance/widgets 0.0.42-beta.99 → 0.0.43-beta.107

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,12 +1,12 @@
1
1
  {
2
2
  "name": "@huma-finance/widgets",
3
- "version": "0.0.42-beta.99+bb1e255",
3
+ "version": "0.0.43-beta.107+ae2881a",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
7
7
  "repository": {
8
8
  "type": "git",
9
- "url": "git+https://github.com/00labs/huma-dapp.git"
9
+ "url": "git+https://github.com/00labs/huma-js.git"
10
10
  },
11
11
  "types": "dist/index.d.ts",
12
12
  "main": "dist/cjs/index.cjs",
@@ -30,8 +30,8 @@
30
30
  "@ethersproject/experimental": "^5.7.0",
31
31
  "@ethersproject/providers": "^5.6.0",
32
32
  "@ethersproject/units": "^5.6.0",
33
- "@huma-finance/sdk": "^0.0.42-beta.99+bb1e255",
34
- "@huma-finance/shared": "^0.0.42-beta.99+bb1e255",
33
+ "@huma-finance/sdk": "^0.0.42",
34
+ "@huma-finance/shared": "^0.0.42",
35
35
  "@mui/icons-material": "^5.3.0",
36
36
  "@mui/material": "^5.0.6",
37
37
  "@mui/styles": "^5.0.2",
@@ -83,12 +83,10 @@
83
83
  "prebuild": "tsc -p tsconfig.build.json",
84
84
  "build": "rollup -c",
85
85
  "cosmos": "cosmos",
86
+ "prettier": "prettier --write \"src/**/*.{js,ts,tsx,graphql}\"",
86
87
  "lint": "eslint --max-warnings=0 \"src/**/*.{js,ts,tsx,graphql}\"",
87
- "lint-staged": "lint-staged",
88
- "e2e": "cypress run --config baseUrl=http://localhost:8000 --headed --browser chrome --e2e",
89
88
  "generateDocs": "jsdoc2md --files \"src/**/*.tsx\" --configure ./jsdoc2md.json > API.md",
90
- "contracts:compile:abi": "typechain --target ethers-v5 --out-dir src/abis/types \"./src/abis/**/*.json\"",
91
- "prettier": "prettier --write \"src/**/*.{js,ts,tsx,graphql}\""
89
+ "lint-staged": "lint-staged"
92
90
  },
93
91
  "husky": {
94
92
  "hooks": {
@@ -96,7 +94,7 @@
96
94
  }
97
95
  },
98
96
  "lint-staged": {
99
- "src/**/*.{js,ts,tsx,css,sass,less,graphql}": [
97
+ "src/**/*.{js,ts,tsx,css,graphql}": [
100
98
  "yarn generateDocs",
101
99
  "eslint --fix --max-warnings=0",
102
100
  "prettier --write",
@@ -194,5 +192,5 @@
194
192
  "optionalDependencies": {
195
193
  "encoding": "^0.1.13"
196
194
  },
197
- "gitHead": "bb1e255865acc0a78dfb78454165676b88582d4d"
195
+ "gitHead": "ae2881aabdb5cd4d64592773477a2c943a397738"
198
196
  }
@@ -0,0 +1,50 @@
1
+ import { supportedChainId } from '@huma-finance/shared'
2
+ import { useWeb3React } from '@web3-react/core'
3
+ import { useEffect, useState } from 'react'
4
+
5
+ import { WCProps } from '../utilTypes'
6
+ import { ErrorModal } from './ErrorModal'
7
+ import { HumaModal, HumaModalHeader } from './humaModal'
8
+
9
+ export function ChainSupportProvider({
10
+ children,
11
+ }: WCProps): React.ReactElement | null {
12
+ const { chainId } = useWeb3React()
13
+ const chainSupported = !!supportedChainId(chainId)
14
+ const [chainNotSupportedOpen, setChainNotSupportedOpen] = useState(false)
15
+
16
+ useEffect(() => {
17
+ setChainNotSupportedOpen(!chainSupported)
18
+ }, [chainSupported])
19
+
20
+ const handleClose = () => {
21
+ setChainNotSupportedOpen(false)
22
+ }
23
+
24
+ if (!chainId) {
25
+ return null
26
+ }
27
+
28
+ if (chainSupported) {
29
+ return children as React.ReactElement
30
+ }
31
+
32
+ return (
33
+ <HumaModal
34
+ isOpen={chainNotSupportedOpen}
35
+ overflowY='auto'
36
+ onClose={handleClose}
37
+ width='480px'
38
+ padding='30px 40px'
39
+ disableBackdropClick
40
+ >
41
+ <HumaModalHeader onClose={handleClose} height={0} />
42
+ <ErrorModal
43
+ title='Network Not Supported'
44
+ errorReason='Please switch to a supported network.'
45
+ handleOk={handleClose}
46
+ okText='Close'
47
+ />
48
+ </HumaModal>
49
+ )
50
+ }
package/src/index.tsx CHANGED
@@ -4,16 +4,13 @@ import { JsonRpcProvider } from '@ethersproject/providers'
4
4
  import {
5
5
  Provider as Web3Provider,
6
6
  ProviderProps as Web3Props,
7
- supportedChainId,
8
7
  } from '@huma-finance/shared'
9
8
  import { ThemeProvider } from '@mui/material'
10
9
  import { Provider as Eip1193Provider } from '@web3-react/types'
11
10
  import { Provider as AtomProvider } from 'jotai'
12
- import { useCallback, useEffect, useState } from 'react'
13
11
  import { Provider as ReduxProvider } from 'react-redux'
14
12
 
15
- import { useWeb3React } from '@web3-react/core'
16
- import { ChainNotSupportedModal } from './components/ChainNotSupportedModal'
13
+ import { ChainSupportProvider } from './components/ChainSupportProvider'
17
14
  import {
18
15
  CreditLineApprove,
19
16
  CreditLineApproveProps,
@@ -55,7 +52,7 @@ type JsonRpcConnectionMap = {
55
52
  * @typedef {Object} WidgetProps
56
53
  * @property {desiredChainId|undefined} desiredChainId Optional desired chain id, will trigger the switch network action if different from the current chain id
57
54
  * @property {JsonRpcConnectionMap|undefined} jsonRpcUrlMap Optional mapping of your JSON-RPC connections indexed by chainId
58
- * @property {Eip1193Provider|JsonRpcProviderl} provider EIP-1193 provider or JsonRpc Provider
55
+ * @property {Eip1193Provider|JsonRpcProvider} provider EIP-1193 provider or JsonRpc Provider
59
56
  */
60
57
  type WidgetProps = {
61
58
  handleClose?: () => void
@@ -66,41 +63,14 @@ type WidgetProps = {
66
63
 
67
64
  function Widget(props: WCProps<WidgetProps>) {
68
65
  const { children } = props
69
- const { chainId } = useWeb3React()
70
-
71
- const chainSupported = !!supportedChainId(chainId)
72
- const [chainNotSupportedOpen, setChainNotSupportedOpen] = useState(false)
73
-
74
- useEffect(() => {
75
- if (chainSupported) {
76
- setChainNotSupportedOpen(false)
77
- } else {
78
- setChainNotSupportedOpen(true)
79
- }
80
- }, [chainSupported])
81
-
82
- const handleCloseCallback = useCallback(() => {
83
- setChainNotSupportedOpen(false)
84
- }, [])
85
-
86
- if (!chainSupported) {
87
- return (
88
- <ThemeProvider theme={themeHuma}>
89
- <ReduxProvider store={store}>
90
- <ChainNotSupportedModal
91
- isOpen={chainNotSupportedOpen}
92
- handleClose={handleCloseCallback}
93
- />
94
- </ReduxProvider>
95
- </ThemeProvider>
96
- )
97
- }
98
66
 
99
67
  return (
100
68
  <ThemeProvider theme={themeHuma}>
101
69
  <ReduxProvider store={store}>
102
70
  <Web3Provider {...(props as Web3Props)}>
103
- <AtomProvider>{children}</AtomProvider>
71
+ <AtomProvider>
72
+ <ChainSupportProvider>{children}</ChainSupportProvider>
73
+ </AtomProvider>
104
74
  </Web3Provider>
105
75
  </ReduxProvider>
106
76
  </ThemeProvider>
@@ -1,62 +0,0 @@
1
- import '@testing-library/cypress/add-commands'
2
- import 'cypress-iframe'
3
-
4
- import {
5
- addressForTx,
6
- INVOICE_AMOUNT,
7
- INVOICE_FACTORED_AMOUNT,
8
- INVOICE_FEES,
9
- ONE_MINUTE,
10
- TWO_MINUTES,
11
- } from '../utils'
12
-
13
- describe('Invoice factoring recurring borrow', () => {
14
- it('Create RN request', () => {
15
- cy.visit(Cypress.env('E2E_TEST_RN_CREATE_BASE_URL'))
16
- cy.findByText('Metamask', { timeout: ONE_MINUTE }).click()
17
- cy.get('input[name="amount"]').type(String(INVOICE_AMOUNT))
18
- cy.get('input[name="payer"]').type(addressForTx)
19
- cy.get('button').contains('Create a request').click()
20
- cy.findAllByText('Request for payment from', {
21
- timeout: TWO_MINUTES,
22
- }).should('exist')
23
- })
24
-
25
- it('Should get paid 80 USDC for an invoice factoring of 100 USDC value', () => {
26
- cy.visit('/')
27
- cy.findByText('InvoiceFactoringBorrow', { timeout: ONE_MINUTE }).click()
28
- const receivedUSDC = INVOICE_FACTORED_AMOUNT - INVOICE_FEES
29
- const remainedUSDC = INVOICE_AMOUNT - INVOICE_FACTORED_AMOUNT
30
- const chooseAmountModalIncrementIcon = '.choose-amount-modal-increment-icon'
31
- const txDoneModalCloseButton = '.transaction-done-modal-close-btn'
32
-
33
- // click the increment icon each time will increment 1 usdc
34
- for (let i = 0; i < INVOICE_FACTORED_AMOUNT; i++) {
35
- cy.iframe()
36
- .find(chooseAmountModalIncrementIcon, { timeout: TWO_MINUTES })
37
- .click()
38
- }
39
-
40
- cy.iframe().find('button').contains('ACCEPT TERMS').click()
41
- cy.iframe().find('div').contains(`${receivedUSDC} USDC`).should('exist')
42
- cy.iframe().find('button').contains('APPROVE TRANSFER').click()
43
-
44
- // wait 2 minutes for transaction to be successful
45
- cy.iframe()
46
- .find(txDoneModalCloseButton, {
47
- timeout: TWO_MINUTES,
48
- })
49
- .should('be.visible')
50
-
51
- cy.iframe()
52
- .find('div')
53
- .contains(`${receivedUSDC} USDC is now in your wallet.`)
54
- .should('exist')
55
- cy.iframe()
56
- .find('div')
57
- .contains(
58
- `The remaining ${remainedUSDC} USDC will be sent to your wallet when the invoice is paid.`,
59
- )
60
- .should('exist')
61
- })
62
- })
@@ -1,76 +0,0 @@
1
- // ***********************************************************
2
- // This file is processed and loaded automatically before your test files.
3
- //
4
- // You can read more here:
5
- // https://on.cypress.io/configuration
6
- // ***********************************************************
7
-
8
- // Import commands.ts using ES2015 syntax:
9
- import { injectedForApprove, injectedForTx } from './ethereum'
10
- import assert = require('assert')
11
-
12
- declare global {
13
- // eslint-disable-next-line @typescript-eslint/no-namespace
14
- namespace Cypress {
15
- interface ApplicationWindow {
16
- ethereum: typeof injectedForTx
17
- }
18
- interface VisitOptions {
19
- serviceWorker?: true
20
- }
21
- }
22
- }
23
-
24
- // sets up the injected provider to be a mock ethereum provider with the given mnemonic/index
25
- // eslint-disable-next-line no-undef
26
- Cypress.Commands.overwrite(
27
- 'visit',
28
- (
29
- original,
30
- url: string | Partial<Cypress.VisitOptions>,
31
- options?: Partial<Cypress.VisitOptions>,
32
- ) => {
33
- assert(typeof url === 'string')
34
-
35
- cy.intercept(
36
- '/service-worker.js',
37
- options?.serviceWorker ? undefined : { statusCode: 404 },
38
- ).then(() => {
39
- original({
40
- ...options,
41
- url:
42
- url.startsWith('/') && url.length > 2 && !url.startsWith('/#')
43
- ? `/#${url}`
44
- : url,
45
- onBeforeLoad(win) {
46
- options?.onBeforeLoad?.(win)
47
- win.localStorage.clear()
48
- win.localStorage.setItem(
49
- 'redux_localstorage_simple_user',
50
- '{"selectedWallet":"INJECTED"}',
51
- )
52
-
53
- win.ethereum = injectedForTx
54
- if (url.endsWith('type=newWallet')) {
55
- win.ethereum = injectedForApprove
56
- }
57
- },
58
- })
59
- })
60
- },
61
- )
62
-
63
- beforeEach(() => {
64
- // Infura security policies are based on Origin headers.
65
- // These are stripped by cypress because chromeWebSecurity === false; this adds them back in.
66
- cy.intercept(/infura.io/, (res) => {
67
- res.headers['origin'] = Cypress.config().baseUrl!
68
- res.continue()
69
- })
70
- })
71
-
72
- Cypress.on('uncaught:exception', (_err, _runnable) => {
73
- // returning false here prevents Cypress from
74
- // failing the test
75
- return false
76
- })
@@ -1,142 +0,0 @@
1
- /**
2
- * Updates cy.visit() to include an injected window.ethereum provider.
3
- */
4
- import { Eip1193Bridge } from '@ethersproject/experimental/lib/eip1193-bridge'
5
- import { ethers } from 'ethers'
6
- import { deepCopy } from 'ethers/lib/utils'
7
-
8
- import {
9
- addressForApprove,
10
- addressForTx,
11
- provider,
12
- signerForApprove,
13
- signerForTx,
14
- } from '../utils'
15
-
16
- class MetamaskBridge extends Eip1193Bridge {
17
- private walletAddress: string
18
-
19
- constructor(
20
- signer: ethers.Signer,
21
- provider: ethers.providers.Provider,
22
- walletAddress: string,
23
- ) {
24
- super(signer, provider)
25
- this.walletAddress = walletAddress
26
- }
27
-
28
- chainId = 5
29
-
30
- async sendAsync(...args: any[]) {
31
- console.debug('sendAsync called', ...args)
32
- return this.send(...args)
33
- }
34
- async send(...args: any[]) {
35
- console.debug('send called', ...args)
36
- const isCallbackForm =
37
- typeof args[0] === 'object' && typeof args[1] === 'function'
38
- let callback
39
- let method
40
- let params
41
- if (isCallbackForm) {
42
- callback = args[1]
43
- method = args[0].method
44
- params = args[0].params
45
- } else {
46
- method = args[0]
47
- params = args[1]
48
- }
49
- if (method === 'eth_requestAccounts' || method === 'eth_accounts') {
50
- if (isCallbackForm) {
51
- callback({ result: [this.walletAddress] })
52
- } else {
53
- return Promise.resolve([this.walletAddress])
54
- }
55
- }
56
- if (method === 'eth_chainId') {
57
- if (isCallbackForm) {
58
- callback(null, { result: '0x5' })
59
- } else {
60
- return Promise.resolve('0x5')
61
- }
62
- }
63
- // Eip1193Bridge only supports eth_sign
64
- // address is the first param for eth_sign
65
- if (method === 'personal_sign') {
66
- method = 'eth_sign'
67
- const [data, address] = deepCopy(params)
68
- params[0] = address
69
- params[1] = data
70
- }
71
- try {
72
- // Please refer to: https://github.com/ethers-io/ethers.js/issues/1683
73
- // If from is present on eth_call it errors, removing it makes the library set
74
- // from as the connected wallet which works fine
75
- if (params && params.length && method === 'eth_call') {
76
- if (params[0].from) {
77
- delete params[0].from
78
- }
79
- if (params[0].gas) {
80
- delete params[0].gas
81
- }
82
- }
83
-
84
- let result
85
- // For sending a transaction if we call send it will error
86
- // as it wants gasLimit in sendTransaction but hexlify sets the property gas
87
- // to gasLimit which makes sensd transaction error.
88
- // This have taken the code from the super method for sendTransaction and altered
89
- // it slightly to make it work with the gas limit issues.
90
- if (
91
- params &&
92
- params.length &&
93
- params[0].from &&
94
- method === 'eth_sendTransaction'
95
- ) {
96
- // Hexlify will not take gas, must be gasLimit, set this property to be gasLimit
97
- params[0].gasLimit = params[0].gas
98
- delete params[0].gas
99
- // If from is present on eth_sendTransaction it errors, removing it makes the library set
100
- // from as the connected wallet which works fine
101
- delete params[0].from
102
- const req = ethers.providers.JsonRpcProvider.hexlifyTransaction(
103
- params[0],
104
- )
105
- // Hexlify sets the gasLimit property to be gas again and send transaction requires gasLimit
106
- req.gasLimit = req.gas
107
- delete req.gas
108
- // Send the transaction
109
- const tx = await this.signer.sendTransaction(req)
110
- result = tx.hash
111
- } else {
112
- // All other transactions the base class works for
113
- result = await super.send(method, params)
114
- }
115
- console.debug('result received', method, params, result)
116
- if (isCallbackForm) {
117
- callback(null, { result })
118
- } else {
119
- return result
120
- }
121
- } catch (error) {
122
- console.log(error)
123
- if (isCallbackForm) {
124
- callback(error, null)
125
- } else {
126
- throw error
127
- }
128
- }
129
- }
130
- }
131
-
132
- export const injectedForTx = new MetamaskBridge(
133
- signerForTx,
134
- provider,
135
- addressForTx,
136
- )
137
-
138
- export const injectedForApprove = new MetamaskBridge(
139
- signerForApprove,
140
- provider,
141
- addressForApprove,
142
- )
@@ -1,9 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "strict": true,
4
- "target": "es5",
5
- "lib": ["es5", "dom"],
6
- "types": ["cypress"]
7
- },
8
- "include": ["**/*.ts"]
9
- }
@@ -1,54 +0,0 @@
1
- import { JsonRpcProvider } from '@ethersproject/providers'
2
- import { Wallet } from '@ethersproject/wallet'
3
- import { ethers } from 'ethers'
4
-
5
- export const ONE_SECOND = 1 * 1000
6
- export const THREE_SECONDS = 3 * 1000
7
- export const FIVE_SECONDS = 5 * 1000
8
- export const TEN_SECONDS = 10 * 1000
9
- export const TWENTY_SECONDS = 20 * 1000
10
- export const ONE_MINUTE = 60 * 1000
11
- export const TWO_MINUTES = 120 * 1000
12
- export const INVOICE_AMOUNT = 100
13
- export const INVOICE_FACTORED_AMOUNT = 80
14
- export const INVOICE_FEES = 8
15
-
16
- const chain = { name: 'Goerli', chainId: 5 }
17
- const infuraKey = Cypress.env('E2E_TEST_INFURA_GOERLI')
18
- export const provider = new JsonRpcProvider(infuraKey, chain)
19
-
20
- export const privateKeyForTx = Cypress.env('E2E_TEST_PRIVATE_KEY')
21
- export const addressForTx = new Wallet(privateKeyForTx).address
22
- export const signerForTx = new Wallet(privateKeyForTx, provider)
23
-
24
- const wallet = ethers.Wallet.createRandom()
25
- export const addressForApprove = wallet.address
26
- export const signerForApprove = new Wallet(wallet.privateKey, provider)
27
-
28
- export const toNumber = (text: string) => {
29
- return Number(text.replace('$', '').replace(/,/g, '').replace('%', ''))
30
- }
31
-
32
- export const getWalletAddressAbbr = (address: string) => {
33
- if (!address) {
34
- return address
35
- }
36
- const { length } = address
37
- return `${address.slice(0, 6)}...${address.slice(length - 4, length)}`
38
- }
39
-
40
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
41
- export const isEmpty = (value: undefined | null | any) =>
42
- value === undefined || value === null
43
-
44
- const formatter = new Intl.NumberFormat('en-US', {
45
- style: 'currency',
46
- currency: 'USD',
47
- })
48
-
49
- export const formatMoney = (num: number | string | undefined) => {
50
- if (isEmpty(num) || Number.isNaN(num)) {
51
- return num
52
- }
53
- return formatter.format(Number(num))
54
- }
package/cypress.config.ts DELETED
@@ -1,20 +0,0 @@
1
- import { defineConfig } from 'cypress'
2
-
3
- export default defineConfig({
4
- projectId: 'yq9qu9',
5
- videoUploadOnPasses: false,
6
- defaultCommandTimeout: 10000,
7
- chromeWebSecurity: false,
8
- e2e: {
9
- testIsolation: false,
10
- setupNodeEvents(on, config) {
11
- return {
12
- ...config,
13
- // Only enable Chrome.
14
- // Electron (the default) has issues injecting window.ethereum before pageload, so it is not viable.
15
- browsers: config.browsers.filter(({ name }) => name === 'chrome'),
16
- }
17
- },
18
- specPattern: 'cypress/e2e/**/*.{js,jsx,ts,tsx}',
19
- },
20
- })
@@ -1,33 +0,0 @@
1
- import React from 'react'
2
-
3
- import { ErrorModal } from './ErrorModal'
4
- import { HumaModal, HumaModalHeader } from './humaModal'
5
-
6
- type Props = {
7
- handleClose: () => void
8
- isOpen: boolean
9
- }
10
-
11
- export function ChainNotSupportedModal({
12
- handleClose,
13
- isOpen,
14
- }: Props): React.ReactElement | null {
15
- return (
16
- <HumaModal
17
- isOpen={isOpen}
18
- overflowY='auto'
19
- onClose={handleClose}
20
- width='480px'
21
- padding='30px 40px'
22
- disableBackdropClick
23
- >
24
- <HumaModalHeader onClose={handleClose} height={0} />
25
- <ErrorModal
26
- title='Network Not Supported'
27
- errorReason='Please switch to a supported network.'
28
- handleOk={handleClose}
29
- okText='Close'
30
- />
31
- </HumaModal>
32
- )
33
- }