Skip to content
This repository has been archived by the owner on Jun 7, 2024. It is now read-only.

Commit

Permalink
Feat/merge (#161)
Browse files Browse the repository at this point in the history
* docs

* update version (#109)

* Revert "update version (#109)" (#110)

This reverts commit 72efce3.

* Fix docs (#105)

* Fix @link to correct class name

`EthersModalConnect` does not exist, I suppose you meant `EthersModalConnector`

* Fix incorrect markdown links

* Fix some confusing wording (probably copy paste leftovers)

Co-authored-by: Shravan Sunder <[email protected]>

* updated docs

* Feature/#96 eth-hook v4 initial dev (#103)

* #96 #94 #93 working on ContractContext.  Started eth context override

* #94 ethersContext overrides for hooks

* #94 ethersContext overrides for hooks.  enable secondary/alternate web3context

* #94 v3.4 will not have getters and setters

* #96 added comments

* fixing merge conflicts, disabled some tests temporarily, changed command name

* Update useGetUserFromSigners.ts

* Additionally #94 #102 Merge branch 'develop' into feature/#96

# Conflicts:
#	package.json
#	src/context/EthersAppContext.tsx
#	src/hooks/useBalance.ts
#	src/hooks/useContractExistsAtAddress.ts
#	src/hooks/useContractLoader.ts
#	src/hooks/useContractReader.ts
#	src/hooks/useGetUserFromProviders.ts
#	src/hooks/useGetUserFromSigners.ts

* update version (#111)

* #101 #94 updates for contracts context changes

* #101 #94 updates for contracts context changes

- created an contract context factory

* #101 #94 some work on generics for definitions

* #101 #94 typing for contracts and factory seems to be working

issues with app contract definition types

* #101 #94 moved some files around

* #101 #94 Finally go the contract typeing to work.  Now i need to work on the reducer

* #101 #94 moved logic from class into reducer

* #101 #94 checkpoint

* #101 #94 organization and refactoring of names and contractAppContext related files.

also renamed harness to wrapper

* #101 #94 more refactoring of types

* #101 #94 fixing types for the contract actions

* #101 #94 fixing types for the contract actions

* #101 #94 created hook and system to load contracts

* #95 added update tuples (getters).  Additionally updated useContractReader to be typed.

- left the old contractReader with untyped postfix
- removed useOnRepetition and updated useBlockNumber
- updated optional provider for many hooks
- removed useWeb3Modal

* #95 added update tuples (getters).

* #95 updated packages and fixed some bugs

* #95 updated yarn and set node version

* #95 refactoring and fixes

* #95 fixes for compatability of eht-hooks and components

* #95 #101 #94 bug fixes and manual testing

* #95 #101 #94 bug fixes and manual testing.  fixing issues with loading contracts in multiple networks

* #95 #101 #94 converted the context back into a reducer

* #95 #101 #94 changes to hook options.  found invariant-ts

* #95 #101 #94 fixed issues with loading contracts

* #95 #101 #94 fixed logs

* #95 #101 #94 fixed  bugs and removed async hook

Co-authored-by: Jaxcoder <[email protected]>

* Feature/#114 (#119)

* #114 integrated react-query and a caching layer for ethereum calls.  in useContractReader and useBalance

- Now ethereum data will be cached and reused based on
- you can now poll, or get data based on new blocks, or block number interval

* #114 updates to query namespace and query invalidation on contract connector load.  updated many hooks to new cached paradigm

* #114 bug fixes to new caching changes

* #114 event based updates.  changes to default options.  all hooks are up to date

* #114 minor bug fix

* #114 context changes.  TODO split apart options

* #114 seperated override from options

* #114 minor workaround for typechain array issue

* #114 better console logs

* #114 imporvements to keys and some hooks.  finished useGasPrice

* #114 new version

* #114 fixes to keys and connectors.  also auto connect for burner options

* #120 #119 created useBalance which accepts single or multiple addresses

- updated contract func key for better caching and invalidation

* updated yarn

* Features/#116 (#121)

* #116 fixed test for useBalance #117 modified wrapper for ContractContext

- removed old json way sof doing things, will be adding local contracts for testing
- updating hardhat mocks

* #116 lots of changes to tests

- cleaned up tests
- fixed old tests
- test wrapper changes to types
- fixed how mocks are loaded
- new mocks for external and hardhat contracts
- updated useContractLoader to be more simple

* #116 bug fixes and updates to contract context

- invalidation of old contract isntances
- key updates
- updates to validate adaptor
- fixes to sorting

* #116 bug fixes and updates to contract context.  Fix to EthersConnector signer bug

- signer should invalidate when chain is changed
- invalidation of old contract isntances
- key updates
- updates to validate adaptor
- fixes to sorting

* #116 changed order of invalidation of cache

* #116 package updates

* #116 package updates

* #116 package updates

* updated actions

* #124 updated docs

* #124 updated readme in docs

* Create CNAME

* Delete CNAME

* Set theme jekyll-theme-minimal

* Set theme jekyll-theme-architect

* Set theme jekyll-theme-midnight

* Set theme jekyll-theme-modernist

* Set theme jekyll-theme-hacker

* Set theme jekyll-theme-architect

* #124 updated docs headers

* #124 added emoji

* chore apply prettier to all files (#128)

biggest changes are just the newlines from windows computers

* Features/#126 (#129)

* #126 added status return type.  made react query options available.  better options typeing

* update packages

* updated tests #126

* Features/#125 (#130)

* updated docs

* #124 updated docs

* #124 updated readme in docs

* Create CNAME

* Delete CNAME

* Set theme jekyll-theme-minimal

* Set theme jekyll-theme-architect

* Set theme jekyll-theme-midnight

* Set theme jekyll-theme-modernist

* Set theme jekyll-theme-hacker

* Set theme jekyll-theme-architect

* #124 updated docs headers

* #124 added emoji

* #125 improved typing and updated to #125.  waiting for eth-sdk to update to v7

* #125 better comments

* #125 some type changes

* #125 some type changes for simplicity

* #126 added status return type.  made react query options available.  better options typeing

* update packages

* updated tests #126

* #125 merged with #126

* added examples and comments and minor changes #126

* comments and readme

* updated README

* updated README

* update package for docs

* updated docs

* #76 Tests for useTokenBalance (#131)

Additionally adds some docs to useTokenBalance and useBalance

* #127 comments and readme

* #124 comments and readme

* Bugs/#133 (#135)

* #133 fixes for contractConnects bugs found in collating contracts for the connectors

* #133 fixes for contractConnects bugs found in collating contracts for the connectors

* #133 nuked lock file

* updated package

* update packages and readme

Co-authored-by: Jaxcoder <[email protected]>
Co-authored-by: omnifient <[email protected]>
Co-authored-by: Sean Paterson <[email protected]>
  • Loading branch information
4 people authored Jan 19, 2022
1 parent cb8d53c commit 99cfe7f
Show file tree
Hide file tree
Showing 184 changed files with 29,735 additions and 20,715 deletions.
3 changes: 2 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,9 @@
}
],
"no-underscore-dangle": [
"warn",
"off",
{
"allow": ["obj"],
"allowFunctionParams": false,
"allowAfterSuper": true,
"allowAfterThis": true,
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/pr-workflow.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ name: Node.js CI
on:
workflow_dispatch:
push:
branches: [next, release]
branches: [release, next]
pull_request:
types: [opened, reopened, ready_for_review, synchronize]

Expand Down Expand Up @@ -36,7 +36,7 @@ jobs:
${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
- run: yarn install --immutable
- run: yarn run es-build
- run: yarn run build

- run: yarn test:hardhat
- name: Publish Unit Test Results
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,6 @@ cache
test/testresult.xml
testresult.xml
.yarn/install-state.gz
test-files/__mocks__/generated
.idea
.DS_store
6 changes: 2 additions & 4 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,9 @@
"**/build/**/*": true,
"**/debug/": true,
"**/dist/": true,
"**/node_modules/": true,
"**/obj": true,
"node_modules": true,
"node_modules/*/**": true,
"lib": true
},
"explorerExclude.backup": null
"explorerExclude.backup": null,
"exportall.config.relExclusion": ["/src/helpers/test-utils", "/src/helpers/typedoc", "/src/helpers/__global.ts"]
}
300 changes: 150 additions & 150 deletions .yarn/releases/yarn-3.1.0.cjs → .yarn/releases/yarn-3.1.1.cjs
100644 → 100755

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions .yarnrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ nodeLinker: node-modules

plugins:
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
spec: '@yarnpkg/plugin-interactive-tools'
spec: "@yarnpkg/plugin-interactive-tools"

yarnPath: .yarn/releases/yarn-3.1.0.cjs
yarnPath: .yarn/releases/yarn-3.1.1.cjs
320 changes: 296 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,39 +1,311 @@
# 🖇 Eth-Hooks Overview
# 🖇 Eth-Hooks

Commonly used Ethereum hooks.
## Overview

Commonly used Ethereum hooks to supercharge your web3 dev!

Used by 🏗 [scaffold-eth](https://github.com/scaffold-eth/scaffold-eth) and 🏭 [scaffold-eth-typescript](https://github.com/scaffold-eth/scaffold-eth-typescript)

Used by 🏗 [scaffold-eth](https://github.com/scaffold-eth/scaffold-eth)
Used by 🏭 [scaffold-eth-typescript](https://github.com/scaffold-eth/scaffold-eth-typescript)
Used by ⚙ [eth-components](https://github.com/scaffold-eth/eth-components)

Created by 🏰 [BuidlGuidl.eth](https://BuidlGuidl.com)

## Install
### Author

[@shravansunder](https://github.com/ShravanSunder)

### Contributors

- [@ss6](https://github.com/ssp6)

## Features

> See this [video summary on v4 features](https://www.youtube.com/watch?v=STxAdE8wQwY)!
### EthersAppContext

A context that allows you to access the current ethers.js context and information such as provider, signer, account. This allows your user to easily log into web3 account using web3modal. You can setup up overrides and multiple providers.

### ContractAppContext

Gives you a `contractContextFactory` that allows you to easily setup typed contracts, load typed contracts, create connectors, and access them with hooks anywhere in your app.

### Caching & optional updates

Caches the network RPC calls so that unecessary requests to the network is prevented. You can setup an update interval from every block, every (n) blocks, polling, onMount, onWindow focus and other react-query update options.

### Hooks!

Ethers App Context

- useBlockNumberContext
- useEthersContext

Network

- useBalance
- useBlockNumber
- useContractExistsAtAddress
- useEventListener
- useGasPrice
- useNonce
- useSignerAddress

Contracts

- useContractReader
- contractContextFactory
- useLoadAppContracts
- useConnectAppContracts
- useConnectAppContracts
- legacy (eth-hooks v2+)
- useContractLoader
- useContractReaderUntyped

ERC

- useTokenBalance

Dapps

- useDexEthPrice
- useDexTokenList
- useResolveEnsAddress
- useResolveEnsName

Utility

- useBurnerSigner

## Quickstart

### Install

```sh
yarn add eth-hooks
```

## Authors
### Setting up the context for eth-hooks

[@austinGriffith](https://github.com/austintgriffith)
[@shravansunder](https://github.com/ShravanSunder)
Add the contexts to your app

```ts
<ContractsAppContext>
<EthersAppContext>
<YourMainPage />
</EthersAppContext>
</ContractsAppContext>
```

> You can see an example of providers in scaffold-eth-typescript [app.tsx](https://github.com/scaffold-eth/scaffold-eth-typescript/blob/next/packages/vite-app-ts/src/App.tsx)
### Using the ethersAppContext & hooks

An example of using the context

```ts
const ethersContext = useEthersContext();
// you now have access to signer, provider, account (address), etc... See IEthersContext for details
```

An example of using a hook

```typescript
// ---------------------
// 🏦 get your balance
// ---------------------
// This instance uses the provider from the context in useBalance internally
const [yourLocalBalance, update, status] = useBalance(ethersContext.account);
Z;
```

An example of changing an update interval

```ts
// normally the hooks update every block
const [yourLocalBalance, update, status] = useBalance(ethersContext.account);
// you can change the update schedule to every 10 blocks, the default is every 1 block:
const [yourLocalBalance, update, status] = useBalance(ethersContext.account, { blockNumberInterval: 10 });
// you can change the update schedule to every polling, min is 10000ms
const [yourLocalBalance, update, status] = useBalance(ethersContext.account, {
refetchInterval: 100000,
blockNumberInterval: undefined,
});
// you can use advanced react-query update options
const [yourLocalBalance, update, status] = useBalance(ethersContext.account, {
blockNumberInterval: 1,
query: { refetchOnWindowFocus: true },
});
```

An example of overriding the provider from the context

```ts
// get an adaptor from a provider or signer
const [mainnetAdaptor] = useEthersAdaptorFromProviderOrSigners(exampleMainnetProvider);
// pass in the override variable
const [yourMainnetBalance] = useBalance(ethersContext.account, mergeDefaultUpdateOptions(), {
adaptorEnabled: true,
adaptor: mainnetAdaptor,
});
```

> Check out examples in scaffold-eth-typescript in [useScaffoldHooksExamples.tsx](https://github.com/scaffold-eth/scaffold-eth-typescript/blob/next/packages/vite-app-ts/src/components/main/hooks/useScaffoldHooksExamples.tsx)
### Using ContractAppContext

#### 1. Generating types for your contract

The first thing you'll have to do is generate your contrac types for hardhat and external contracts. Add `eth-sdk` or `typechain with hardhat` to generate that to a folder such as `generated/contract-types`. Pull [scaffold-eth-typescript](https://github.com/scaffold-eth/scaffold-eth-typescript) for an example of this.

##### An example on to use eth-sdk for external contracts

scaffold-eth-typescript uses `eth-sdk` to generate types and abi for external contracts using. See the excellent documentation there for this at [eth-sdk github](https://github.com/dethcrypto/eth-sdk). 📝 Note that this would a dev dependency on your project.

- a config of `{contractNames: address}` [externalContractConfig.ts](https://github.com/scaffold-eth/scaffold-eth-typescript/blob/next/packages/vite-app-ts/src/config/externalContractsConfig.ts)
- a config for [eth-sdk-config.ts](https://github.com/scaffold-eth/scaffold-eth-typescript/blob/next/packages/vite-app-ts/scripts/eth-sdk-config.ts.bak)
- and calling the `eth-sdk` with the folder of your config file as a parameter e.g. `yarn eth-sdk -p ./src/generated`

##### An example of using hardhat with typechain

> Check out the excellent [typechain docs](https://github.com/dethcrypto/TypeChain). You can find an example in scaffold-eth-typescript [hardhat.config.ts](https://github.com/scaffold-eth/scaffold-eth-typescript/blob/next/packages/hardhat-ts/hardhat.config.ts)
#### 2. Creating the context with contractsContextFactory

You'll have to create a config that returns a config of your contracts. This would be hetrogenous key value pair. each value is generated by the helper functions in eth-hooks.

For example:

```ts
// a function that generates the config. Note that your types have to exist already!
export const contractConnectorConfig = () => {
try {
const result = {
// 🙋🏽‍♂️ Add your hadrdhat contracts here
YourContract: createConnectorForHardhatContract(
'YourContract',
hardhatContracts.YourContract__factory,
hardhatContractsJson
),

// 🙋🏽‍♂️ Add your external contracts here, make sure to define the address in `externalContractsConfig.ts`
DAI: createConnectorForExternalContract('DAI', externalContracts.DAI__factory, externalContractsAddressMap),
UNI: createConnectorForExternalContract('UNI', externalContracts.UNI__factory, externalContractsAddressMap),

// 🙋🏽‍♂️ Add your external abi here (unverified contracts)`
// DAI: createConnectorForExternalAbi('DAI', { 1: {address: 'xxxx'}}, abi),
} as const;

return result;
} catch (e) {
console.error(
'❌ contractConnectorConfig: ERROR with loading contracts please run `yarn contracts:build or yarn contracts:rebuild`. Then run `yarn deploy`!',
e
);
}

return undefined;
};

// create a type from the return value of the function above
export type TAppConnectorList = NonNullable<ReturnType<typeof contractConnectorConfig>>;
```

Use `contractContextFactory` to create your hooks and context in your app from the above configuration. You could just copy the blow and use it.

```ts
// you're passing in function `contractConnectorConfig` from above into the factory. You then have to use the type we defined to type the factory outputs.
export const {
ContractsAppContext,
useAppContractsActions,
useAppContracts,
useLoadAppContracts,
useConnectAppContracts,
} = contractsContextFactory<
/* the contractNames (keys) in config output */
keyof TAppConnectorList,
/* the type of the config output */
TAppConnectorList,
/* A type that infers the value of each contractName: contract pair*/
TTypedContract<keyof TAppConnectorList, TAppConnectorList>
>(contractConnectorConfig);
```

> See scaffold-eth-typescript [contractContext.tsx](https://github.com/scaffold-eth/scaffold-eth-typescript/blob/next/packages/vite-app-ts/src/config/contractContext.ts) and [contractConnectorConfig.ts](https://github.com/scaffold-eth/scaffold-eth-typescript/blob/next/packages/vite-app-ts/src/config/contractConnectorConfig.ts) for full examples on how to do this.
#### 3. Using hooks to get your contracts

Now that you've created the context and hooks above you can use them in your app. The first step is to load your contracts using the hooks you've created with the factory.

```ts
// 🛻 load contracts
useLoadAppContracts();
```

Next you'll want to connect the contracts.

```ts
// 🏭 connect to contracts for current network & signer
useConnectAppContracts(asEthersAdaptor(ethersContext));

// 🏭 connect to contracts for mainnet network & signer
const [mainnetAdaptor] = useEthersAdaptorFromProviderOrSigners(mainnetProvider);
useConnectAppContracts(mainnetAdaptor);
```

Now you can get typed contracts anywhere in your

```ts
const yourContract = useAppContracts('YourContract', ethersContext.chainId);
const mainnetDai = useAppContracts('DAI', NETWORKS.mainnet.chainId);
```

You can read values from the contracts using the `useContractReader` hook

```ts
// keep track of a variable from the contract in the local React state:
const [purpose, update] = useContractReader(
/* the contract */
yourContract,
/* the contract variable or function to read */
yourContract?.purpose,
/* the arguments, they are typed tuple */
[],
/* optional: if you want your contracts to only update on event */
yourContract?.filters.SetPurpose()
);

// keep track of a variable from the contract in the local React state:
const [purpose, update] = useContractReader(
/* the contract */
yourContract,
/* the contract variable or function to read */
yourContract?.purpose,
/* the arguments, they are typed tuple */
[],
undefined,
/* optional: update every 10 blocks */
{ blockNumberInterval: 10 }
);
```

## API Documentation

Check out [the documentation here!](https://scaffold-eth.github.io/eth-hooks/)

The documentation are also available on [scaffold-eth's gitbook](https://docs.scaffoldeth.io/scaffold-eth-libraries/v/eth-hooks-v3/)

## Dependencies

- peer dependencies
- react/react-dom
- web3
- @uniswap/sdk
- dependencies
- ethers
- web3-react
- web3modal
- test utilities dependencies: `/helpers/test-utils`
- hardhat/hardhat-waffle/hardhat-ethers
- waffle

# API Docs

- [Docs @gitbook](https://docs.scaffoldeth.io/scaffold-eth-libraries/v/eth-hooks-v3/)
- [Docs @github.io](https://scaffold-eth.github.io/eth-hooks/)
### Main package dependencies

- ethers.js
- @uniswap/token-lists
- @web3-react: core, abstractconnector, types
- web3modal
- react-query

### Peer dependencies

- react, react/dom
- uniswap/sdk
Loading

0 comments on commit 99cfe7f

Please sign in to comment.