@web3-react/injected-connector#InjectedConnector JavaScript Examples
The following examples show how to use
@web3-react/injected-connector#InjectedConnector.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: logic.js From lrc-staking-dapp with MIT License | 8 votes |
tryToOpenWalletIfNotActive = (active, walletID, onActivate, onSetWalletID) => {
if (!active) {
switch (walletID) {
case 1: // Read-only
onActivate(new NetworkConnector({ urls: { 1: 'https://mainnet.infura.io/v3/740f8a307aa34141a298506577f063bc' } }))
.catch(() => onSetWalletID(0));
break;
case 2: // Metamask
onActivate(new InjectedConnector({ supportedChainIds: [1, 3, 4, 5, 42] }))
.catch(() => onSetWalletID(0));
break;
case 3:
onActivate(new LedgerConnector({ chainId: 1, url: 'https://mainnet.infura.io/v3/740f8a307aa34141a298506577f063bc' }))
.catch(() => onSetWalletID(0));
break;
case 4:
onActivate(new TrezorConnector({
chainId: 1,
manifestAppUrl: 'https://stake.o2b.dev',
manifestEmail: '[email protected]',
url: 'https://mainnet.infura.io/v3/740f8a307aa34141a298506577f063bc',
}))
.catch(() => onSetWalletID(0));
break;
case 5:
onActivate(new WalletConnectConnector({ rpc: { 1: 'https://mainnet.infura.io/v3/740f8a307aa34141a298506577f063bc' } }))
.catch(() => onSetWalletID(0));
break;
case 6:
onActivate(new AuthereumConnector({ chainId: 1 }))
.catch(() => onSetWalletID(0));
break;
case 7:
onActivate(new FortmaticConnector({ apiKey: 'pk_live_01129497FC783931', chainId: 1 }))
.catch(() => onSetWalletID(0));
break;
case 8:
onActivate(new PortisConnector({ dAppId: '0e834d4c-cea9-4770-9c52-679fe5580bad', networks: [1] }))
.catch(() => onSetWalletID(0));
break;
case 9:
onActivate(new SquarelinkConnector({ clientId: '', networks: [1] }))
.catch(() => onSetWalletID(0));
break;
case 10:
onActivate(new TorusConnector({ chainId: 1 }))
.catch(() => onSetWalletID(0));
break;
default: // No wallet
onSetWalletID(0);
break;
}
}
}
Example #2
Source File: Authenticate.jsx From locked.fyi with MIT License | 7 votes |
Authenticate = () => {
const { activate } = useWeb3React()
const injectedConnector = new InjectedConnector({
supportedChainIds: [1, 3, 4, 5, 42],
})
const walletConnectConnector = new WalletConnectConnector({
rpc: {
1: "https://eth-mainnet.alchemyapi.io/v2/GUEohLZ1A5Sv0e5mnfOu0lvF6kwfgkyc",
},
bridge: "https://bridge.walletconnect.org",
qrcode: true,
pollingInterval: 12000,
})
return (
<Buttons>
<AuthenticateButton onClick={() => activate(injectedConnector)}>
Log-in
</AuthenticateButton>
<WalletConnectButton onClick={() => activate(walletConnectConnector)}>
<Qr height={20} width={20} />
</WalletConnectButton>
</Buttons>
)
}
Example #3
Source File: Wallet.js From tulip-frontend with GNU Affero General Public License v3.0 | 7 votes |
function WalletProvider({ children }) {
return (
<UseWalletProvider
chainId={env('CHAIN_ID')}
connectors={{
injected: {
web3ReactConnector({ chainId }) {
return new InjectedConnector({
supportedChainIds: getSupportedChains(),
})
},
handleActivationError(err) {
if (err instanceof InjectedUserRejectedRequestError) {
return new ConnectionRejectedError()
}
},
},
}}
>
<WalletAugmented>{children}</WalletAugmented>
</UseWalletProvider>
)
}
Example #4
Source File: index.js From Artion-Client with GNU General Public License v3.0 | 6 votes |
injected = new InjectedConnector({
supportedChainIds: isMainnet
? [
250, // fantom
]
: [
4002, // fantom testnet
],
})
Example #5
Source File: utils.js From dshop with MIT License | 6 votes |
injectedConnector = new InjectedConnector()
Example #6
Source File: utils.js From dshop with MIT License | 6 votes |
injectedConnector = new InjectedConnector()
Example #7
Source File: connectors.js From vote-incentives with GNU General Public License v3.0 | 5 votes |
injected = new InjectedConnector({
supportedChainIds: [1, 3, 4, 5, 42]
})
Example #8
Source File: connectors.jsx From yuni.finance with MIT License | 5 votes |
injected = new InjectedConnector({
supportedChainIds: [1]
})
Example #9
Source File: connectors.jsx From ygov-finance with MIT License | 5 votes |
injected = new InjectedConnector({
supportedChainIds: [1, 3, 4, 5, 42]
})
Example #10
Source File: connectors.jsx From ycredit-finance with MIT License | 5 votes |
injected = new InjectedConnector({
supportedChainIds: [1, 3, 4, 5, 42]
})
Example #11
Source File: connectors.jsx From iliquidate-finance with MIT License | 5 votes |
injected = new InjectedConnector({
supportedChainIds: [1, 3, 4, 5, 42]
})
Example #12
Source File: connectors.jsx From ileverage-finance with MIT License | 5 votes |
injected = new InjectedConnector({
supportedChainIds: [1, 3, 4, 5, 42]
})
Example #13
Source File: index.js From Smart-Swap-Protocol with GNU General Public License v3.0 | 5 votes |
injected = new InjectedConnector({
supportedChainIds: [Number("8995")]
})
Example #14
Source File: connectors.js From pure.finance with MIT License | 5 votes |
injected = new InjectedConnector({
supportedChainIds: [1, 1337, 31337]
})
Example #15
Source File: index.js From pine-interface with GNU General Public License v3.0 | 5 votes |
injected = new InjectedConnector({
supportedChainIds: [1, 3, 4, 5, 42]
})
Example #16
Source File: connectors.jsx From keep3r.governance with MIT License | 5 votes |
injected = new InjectedConnector({
supportedChainIds: [1, 3, 4, 5, 42]
})
Example #17
Source File: index.js From sorbet-finance with GNU General Public License v3.0 | 5 votes |
injected = new InjectedConnector({
supportedChainIds: [
1, // mainnet
3, // ropsten
137, // matic
],
})
Example #18
Source File: connectors.jsx From crv.finance with MIT License | 5 votes |
injected = new InjectedConnector({
supportedChainIds: [1, 3, 4, 5, 42]
})
Example #19
Source File: App.js From gnosis-safe-delegate-dapp with MIT License | 5 votes |
injectedConnector = new InjectedConnector({ supportedChainIds: supportedChainID })
Example #20
Source File: connectors.js From origin-dollar with MIT License | 5 votes |
injectedConnector = new InjectedConnector({
supportedChainIds: [1, 1337],
})
Example #21
Source File: index.js From semaphore_auth with MIT License | 5 votes |
MetaMask = new InjectedConnector({
supportedChainIds: [supportedNetwork]
})
Example #22
Source File: index.js From acy-dex-interface with MIT License | 5 votes |
injected = new InjectedConnector({
supportedChainIds: [1, 3, 4, 5, 42, 56, 97, 137, 42161, 80001],
//supportedChainIds: [56, 97, 137, 80001],
// supportedChainIds: [56, 97],
})
Example #23
Source File: index.js From acy-dex-interface with MIT License | 5 votes |
injectedConnector = new InjectedConnector({
supportedChainIds
})
Example #24
Source File: _Helpers.js From acy-dex-interface with MIT License | 5 votes |
injectedConnector = new InjectedConnector({
supportedChainIds
})
Example #25
Source File: index.js From uniswap-v1-frontend with GNU General Public License v3.0 | 5 votes |
injected = new InjectedConnector({
supportedChainIds: [Number(process.env.REACT_APP_CHAIN_ID)]
})
Example #26
Source File: AccountInfo.js From acy-dex-interface with MIT License | 4 votes |
function AccountInfo(props) { const INITIAL_ROW_NUMBER = 5; const [isWatchlist, setIsWatchlist] = useState(false); const [tableRow, setTableRow] = useState([]); const [rowNumber, setRowNumber] = useState(INITIAL_ROW_NUMBER); const [walletConnected, setWalletConnected] = useState(false); const { activate } = useWeb3React(); const {account, library, chainId} = useConstantLoader(); const [liquidityPositions, setLiquidityPositions] = useState([]); const [activePosition, setActivePosition] = useState(null); const [isMyFarms, setIsMyFarms] = useState(false); const [harvestAcy, setHarvestAcy] = useState(); const [balanceAcy, setBalanceAcy] = useState(); const [stakeACY, setStakeACY] = useState(); const [isLoadingPool, setIsLoadingPool] = useState(true); const [isLoadingHarvest, setIsLoadingHarvest] = useState(true); const [isLoadingBalance, setIsLoadingBalance] = useState(true); //Wallet State Value Store const [userLiquidityOwn,setOwn] = useState(0); const [userLiquidityEarn, setEarn] = useState(0); // Fetch Account Transactions const [userTransactions, setUserTransactions] = useState(null) // wallet analytics const [totalNoOfTransactions, setTotalNoOfTransactions] = useState(0) const [totalValueSwapped, setTotalValueSwapped] = useState(0) const [totalFeesPaid, setTotalFeesPaid] = useState(0) const [liquidityIncludingFees, setLiquidityIncludingFees] = useState(0) const [userLPHandlers, setUserLPHandlers] = useState([]); // const [userLPData, setUserLPData] = useState([]); // fetch a list of valid pool from backend const [userLPShares, setUserLPShares] = useState([]); const injected = new InjectedConnector({ supportedChainIds: [1, 3, 4, 5, 42, 56, 97, 80001], }); const { address } = useParams(); useEffect(() => { // fetch user transaction data if(library) { fetchAccountTransaction(account, library).then(accountTransactions => { console.log('accountTransactions', accountTransactions); if (accountTransactions) { setUserTransactions(accountTransactions); console.log(accountTransactions); }; }); } }, [library]); useEffect(() => { if (library) { // fetch total value swapped fetchTotalValueSwapped(account).then(valueSwapped => { setTotalValueSwapped(valueSwapped); }) // fetch total fees paid fetchTotalFeesPaid(account).then(feesPaid => { setTotalFeesPaid(feesPaid); }) // fetch total transactions fetchTotalTransactions(account).then(noOfTransactions => { setTotalNoOfTransactions(noOfTransactions); }) // fetch liquidity including fees fetchLiqudityIncludingFees(account).then(liquidityFees => { setLiquidityIncludingFees(liquidityFees); }) } }, [library]) // method to hide/unhidden table row. const onRowClick = index => setTableRow(prevState => { const prevTableRow = [...prevState]; prevTableRow[index].hidden = !prevTableRow[index].hidden; return prevTableRow; }); // method to prompt metamask extension for user to connect their wallet. useEffect( () => { // console.log("TEST HERE ADDRESS:",address); // fetchPoolsFromAccount(marketClient, address).then(data => { // setLiquidityPositions(data); // }); // const getPools = async (library, account) => { // // get all pools from the farm contract. // // todo: currently account refers to the current user viewing this webpage, // // todo: needs to be change to the user in this webpage. // const pools = (await getAllPools(library, account)).filter(pool => pool.hasUserPosition); // const newFarmsContents = []; // const block = await library.getBlockNumber(); // // format pools data to the required format that the table can read. // pools.forEach(pool => { // const newFarmsContent = { // index: 0, // poolId: pool.poolId, // lpTokens: pool.lpTokenAddress, // token1: pool.token0Symbol, // token1Logo: getLogoURIWithSymbol(pool.token0Symbol), // token2: pool.token1Symbol, // token2Logo: getLogoURIWithSymbol(pool.token1Symbol), // pendingReward: pool.rewardTokensSymbols.map((token, index) => ({ // token, // amount: pool.rewardTokensAmount[index], // })), // totalApr: pool.apr.toFixed(2), // tvl: pool.tvl.toFixed(2), // hasUserPosition: pool.hasUserPosition, // hidden: true, // userRewards: pool.rewards, // stakeData: pool.stakeData, // poolLpScore: pool.lpScore, // poolLpBalance: pool.lpBalance, // endsIn: getDHM((pool.endBlock - block) * BLOCK_TIME), // status: pool.endBlock - block > 0, // ratio: pool.ratio, // endAfter: (pool.endBlock - block) * BLOCK_TIME, // }; // if(newFarmsContent.poolId == 0) { // // const total = rewards[j].reduce((total, currentAmount) => total.add(parseInt(currentAmount))); // if(newFarmsContent.stakeData){ // const myStakeAcy = newFarmsContent.stakeData.reduce((total, currentAmount) => total + parseFloat(currentAmount.lpAmount), 0); // setStakeACY({ // myAcy: myStakeAcy, // totalAcy: newFarmsContent.poolLpBalance // }); // } else { // setStakeACY({ // myAcy: 0, // totalAcy: newFarmsContent.poolLpBalance // }); // } // } // newFarmsContents.push(newFarmsContent); // }); // setTableRow(newFarmsContents); // setIsLoadingPool(false); // }; // account will be returned if wallet is connected. // so if account is present, retrieve the farms contract. if (account) { setWalletConnected(true); // getPools(library, account); // initDao(library, account); } else { setWalletConnected(false); } }, [account] ); const dynamicPositions = activePosition ? [activePosition] : liquidityPositions; const aggregateFees = dynamicPositions?.reduce((total, position) => { return total + (isNaN(position.fees.sum) ? 0 : position.fees.sum); }, 0); const positionValue = useMemo( () => { if (!dynamicPositions) return; const reduced = dynamicPositions ? dynamicPositions.reduce((total, position) => { const positionUSDValue = (parseFloat(position.liquidityTokenBalance) / parseFloat(position.pair.totalSupply)) * parseFloat(position.pair.reserveUSD); return total + (isNaN(positionUSDValue) ? 0 : positionUSDValue); }, 0) : null; return reduced; }, [dynamicPositions] ); // calculate the UserLiquidityOwn -------------------------------------------------------------------------------------------------------------- const getValidPoolList = (account) => { // setLoading(true); //const apiUrlPrefix = API_URL(); const apiUrlPrefix = MARKET_API_URL(); console.log("fetching user pool list"); axios.get( // fetch valid pool list from remote `${apiUrlPrefix}/userpool?walletId=${account}` ).then(async res => { console.log("fetch pool data"); console.log(res.data); const supportedTokens = TOKENLIST(); const tokens = supportedTokens; // construct pool list locally const pools = res.data.pools; const fetchTask = []; for (let pairAddr of pools) { const token0addr = supportedTokens.findIndex(item => item.address === pairAddr.token0); const token1addr = supportedTokens.findIndex(item => item.address === pairAddr.token1); const { address: token0Address, symbol: token0Symbol, decimals: token0Decimal } = tokens[token0addr]; const { address: token1Address, symbol: token1Symbol, decimals: token1Decimal } = tokens[token1addr]; const token0 = new Token(chainId, token0Address, token0Decimal, token0Symbol); const token1 = new Token(chainId, token1Address, token1Decimal, token1Symbol); // queue get pair task const pair = Fetcher.fetchPairData(token0, token1, library, chainId); fetchTask.push(pair); console.log("adding task to array") } const pairs = await Promise.allSettled(fetchTask); console.log("fetched pairs", pairs); const LPHandlers = pairs.map(pair => pair.value); setUserLPHandlers(LPHandlers); console.log("userLPHandlers is updated with length", LPHandlers.length); }).catch(e => console.log("error: ", e)); } async function getUserPoolShare() { const fetchPoolShare = async (pair) => { console.log("poolToken,", pair.liquidityToken) let userPoolBalance = await getUserTokenBalanceRaw(pair.liquidityToken, account, library); if (userPoolBalance.isZero()) { console.log("zero balance, discard"); return {}; } userPoolBalance = new TokenAmount(pair.liquidityToken, userPoolBalance); const totalSupply = await getTokenTotalSupply(pair.liquidityToken, library, account); const tokenPrice = await getAllSupportedTokensPrice(); // console.log(tokenPrice['ETH']); const token0Deposited = pair.getLiquidityValue( pair.token0, totalSupply, userPoolBalance, false ); const token1Deposited = pair.getLiquidityValue( pair.token1, totalSupply, userPoolBalance, false ); const poolTokenPercentage = new Percent(userPoolBalance.raw, totalSupply.raw).toFixed(4); const newData = { token0Amount: `${token0Deposited.toSignificant(4)}`, token0Symbol: `${pair.token0.symbol}`, token1Amount: `${token1Deposited.toSignificant(4)}`, token1Symbol: `${pair.token1.symbol}`, share: `${poolTokenPercentage}%`, }; // console.log(tokenPrice[newData.token0Symbol]); //calculate user own in the same time // const token0value = tokenPrice[newData.token0Symbol] * newData.token0Amount; // const token1value = tokenPrice[newData.token1Symbol] * newData.token1Amount; console.log("new data value:"); const valueSum = tokenPrice[newData.token0Symbol] * newData.token0Amount + tokenPrice[newData.token1Symbol] * newData.token1Amount; setOwn(prev => (prev + valueSum)); console.log("userLPShares is updated: ", newData); setUserLPShares(prev => ({ ...prev, [pair.liquidityToken.address]: newData })); console.log("UserLP infomation:"); } (async () => { for (let pair of userLPHandlers) fetchPoolShare(pair); })(); } useEffect(async () => { console.log("the user address is :" + account); console.log("fetching the user pairs information"); getValidPoolList(account); },[account]); useEffect( async () => { if (!chainId || !library || !account || !userLPHandlers) return; console.log("getting user liquidity") await getUserPoolShare(); }, [chainId, library, account, userLPHandlers] ); // Formatter for liquidity including fees const formatString = (value) => { let formattedStr; if (value >= 1000000) { formattedStr = `$${(value / 1000000).toFixed(2)}mil`; } else if (value >= 1000) { formattedStr = `$${(value / 1000).toFixed(2)}k`; } else { formattedStr = `$${(value).toFixed(2)}`; } return formattedStr; } return ( <div className={styles.marketRoot}> { address == account ? ( <div> <MarketSearchBar dataSourceCoin={dataSourceCoin} dataSourcePool={dataSourcePool} // refreshWatchlist={refreshWatchlist} /> {/* breadcrumb */} <div className={styles.infoHeader}> <Breadcrumb separator={<span style={{ color: '#b5b5b6' }}>></span>} style={{ marginBottom: '20px', color: '#b5b5b6' }} > <Breadcrumb.Item> <Link style={{ color: '#b5b5b6' }} to="/market"> Overview </Link> </Breadcrumb.Item> <Breadcrumb.Item> <Link style={{ color: '#b5b5b6' }} to="/market/accounts"> Accounts </Link> </Breadcrumb.Item> <Breadcrumb.Item style={{ fontWeight: 'bold' }}>{address}</Breadcrumb.Item> </Breadcrumb> </div> {/* name, hyperlink, watchlist */} <div className={styles.accountPageRow} style={{ display: 'flex', justifyContent: 'space-between' }} > <div> {/* <div style={{ fontSize: '26px', fontWeight: 'bold' }}>{address}</div> */} <a onClick={() => openInNewTab(`${SCAN_URL_PREFIX()}/address/${address}`)} style={{ color: '#e29227', fontWeight: 600 }} > View on {SCAN_NAME} </a> </div> <AcyIcon name={isWatchlist ? 'star_active' : 'star'} style={{ marginLeft: '10px' }} width={16} onClick={() => setIsWatchlist(!isWatchlist)} /> </div> {/* dropdown */} <div className={styles.accountPageRow}> <PositionDropdown positions={[...new Set(liquidityPositions)]} onPositionClick={setActivePosition} /> </div> {/* wallet stats */} <div className={styles.accountPageRow}> <h2>Wallet Stats</h2> <div style={{ display: 'flex' }} className={styles.walletStatCard}> <div className={styles.walletStatEntry}> <div className={styles.walletStatValue}>{totalValueSwapped}</div> <div className={styles.walletStatIndicator}>Total Value Swapped</div> </div> <div style={{ width: 20 }} /> <div className={styles.walletStatEntry}> <div className={styles.walletStatValue}>{totalFeesPaid}</div> <div className={styles.walletStatIndicator}>Total Fees Paid</div> </div> <div style={{ width: 20 }} /> <div className={styles.walletStatEntry}> <div className={styles.walletStatValue}>{totalNoOfTransactions}</div> <div className={styles.walletStatIndicator}>Total Transactions</div> </div> </div> </div> {/* liquidity and fees earned */} <div className={styles.accountPageRow}> <div style={{ display: 'flex' }} className={styles.walletStatCard}> <div className={styles.walletStatEntry}> <div className={styles.walletStatIndicator}>Liquidity (including fees)</div> <div className={styles.walletStatValue}> {/* {positionValue ? formattedNum(positionValue, true) : positionValue === 0 ? formattedNum(userLiquidityOwn, true) : '-'} */} {formatString(userLiquidityOwn)} </div> </div> <div style={{ width: 20 }} /> {/* <div className={styles.walletStatEntry}> <div className={styles.walletStatIndicator}>Fees earned (cumulative)</div> <div className={styles.walletStatValue} style={{ color: 'greenyellow' }}> {aggregateFees ? formattedNum(aggregateFees, true, true) : userLiquidityEarn} </div> </div> */} </div> </div> {/* graphs */} {/* <div className={styles.accountPageRow}> <div className={styles.accountGraphCard}> <div style={{ display: 'flex', justifyContent: 'space-between' }}> <AcyPeriodTime onhandPeriodTimeChoose={() => {}} times={['Liquidity', 'Fees']} /> <AcyPeriodTime onhandPeriodTimeChoose={() => {}} times={['1W', '1M', 'All']} /> </div> <div style={{ height: '50vh' }}> <AcyAccountChart lineColor="#1e5d91" /> </div> </div> </div> */} {/* positions table */} {/* <div className={styles.accountPageRow}> <h2>Positions</h2> <PositionTable data={samplePositionData} /> </div> */} {/* Farms */} {/* <div className={styles.accountPageRow}> <h2>Farms</h2> { (isLoadingHarvest || isLoadingPool || isLoadingBalance)? ( <div> <PageLoading/> </div> ) : ( <FarmsTable tableRow={tableRow} // onRowClick={onRowClick} tableTitle="User Farms" tableSubtitle="Stake your LP tokens and earn token rewards" rowNumber={rowNumber} setRowNumber={setRowNumber} hideDao={true} selectedTable={0} tokenFilter={false} setTokenFilter={() => {}} walletConnected={walletConnected} connectWallet={connectWallet} account={account} library={library} chainId={chainId} isMyFarms={true} harvestAcy={harvestAcy} balanceAcy={balanceAcy} refreshHarvestHistory={()=>{}} searchInput={''} isLoading={false} activeEnded={true} /> )} </div> */} {/* transaction table */} <div className={styles.accountPageRow}> <h2>Transactions</h2> { !userTransactions ? ( <h2 style={{ textAlign: "center", color: "white" }}>Loading <Icon type="loading" /></h2> ) : ( <TransactionTable dataSourceTransaction={userTransactions} /> )} {/* <TransactionTable dataSourceTransaction={userTransactions} /> */} </div> <div style={{ height: 20 }} /> </div> ): ( <div> Address does not matched with the connected account </div> ) } </div> ); }