ethers#ethers JavaScript Examples
The following examples show how to use
ethers#ethers.
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: utils.js From dshop with MIT License | 7 votes |
getContracts = memoize(async function (provider) {
const factory = new ethers.Contract(Addresses.factory, abi(factC), provider)
const dai = new ethers.Contract(Addresses.dai, abi(ercBurnable), provider)
const ogn = new ethers.Contract(Addresses.ogn, abi(ercBurnable), provider)
const chico = new ethers.Contract(Addresses.chico, abi(ercFixed), provider)
const weth = new ethers.Contract(Addresses.weth, abi(ercFixed), provider)
const pairAddress = await factory.getPair(weth.address, chico.address)
const pair = new ethers.Contract(pairAddress, abi(pairC), provider)
const pairErc20 = new ethers.Contract(pairAddress, abi(pairEC), provider)
const router = new ethers.Contract(Addresses.router, abi(routerC), provider)
const erc20 = Contract(ercFixed)
window.contracts = {
factory,
pair,
pairErc20,
router,
dai,
chico,
erc20,
weth,
ogn
}
return { factory, pair, pairErc20, router, dai, chico, weth, ogn }
})
Example #2
Source File: useCreateDeposit.js From tulip-frontend with GNU Affero General Public License v3.0 | 6 votes |
export function useCreateDeposit(
tokenAddress,
amount,
unlockTime = 0,
referrer = '0x0000000000000000000000000000000000000000',
chainId
) {
// amount = amount !== '' ? ethers.utils.parseEther('0.00000426') : amount
amount = ethers.utils.parseEther(amount)
const network = getNetworkConfig(chainId)
const contract = useContract(network.honeyfarm, honeyFarm)
return () => {
return new Promise((resolve, reject) => {
contract
.createDeposit(tokenAddress, amount, unlockTime, referrer)
.then(x => {
resolve(x)
})
.catch(err => reject(serializeError(err)))
})
}
}
Example #3
Source File: index.jsx From uniswap-v1-frontend with GNU General Public License v3.0 | 6 votes |
function calculateSlippageBounds(value, token = false, tokenAllowedSlippage, allowedSlippage) {
if (value) {
const offset = value.mul(token ? tokenAllowedSlippage : allowedSlippage).div(ethers.utils.bigNumberify(10000))
const minimum = value.sub(offset)
const maximum = value.add(offset)
return {
minimum: minimum.lt(ethers.constants.Zero) ? ethers.constants.Zero : minimum,
maximum: maximum.gt(ethers.constants.MaxUint256) ? ethers.constants.MaxUint256 : maximum
}
} else {
return {}
}
}
Example #4
Source File: index.js From acy-dex-interface with MIT License | 6 votes |
export function usePositionsForOrders(chainId, library, orders) {
const key = orders ? orders.map(order => getOrderKey(order) + '____') : null
const { data: positions = {} } = useSWR(key, async () => {
const provider = getProvider(library, chainId)
const vaultAddress = getContract(chainId, "Vault")
const contract = new ethers.Contract(vaultAddress, Vault.abi, provider)
const data = await Promise.all(orders.map(async order => {
try {
const position = await contract.getPosition(order.account, order.collateralToken, order.indexToken, order.isLong)
if (position[0].eq(0)) {
return [null, order]
}
return [position, order]
} catch (ex) {
console.error(ex)
}
}))
return data.reduce((memo, [position, order]) => {
memo[getOrderKey(order)] = position
return memo
}, {})
})
return positions
}
Example #5
Source File: ethereumFunctions.js From Alternative-Uniswap-Interface with GNU General Public License v3.0 | 6 votes |
// This function returns an object with 2 fields: `balance` which container's the account's balance in the particular token,
// and `symbol` which is the abbreviation of the token name. To work correctly it must be provided with 4 arguments:
// `accountAddress` - An Ethereum address of the current user's account
// `address` - An Ethereum address of the token to check for (either a token or AUT)
// `provider` - The current provider
// `signer` - The current signer
export async function getBalanceAndSymbol(
accountAddress,
address,
provider,
signer,
weth_address,
coins
) {
try {
if (address === weth_address) {
const balanceRaw = await provider.getBalance(accountAddress);
return {
balance: ethers.utils.formatEther(balanceRaw),
symbol: coins[0].abbr,
};
} else {
const token = new Contract(address, ERC20.abi, signer);
const tokenDecimals = await getDecimals(token);
const balanceRaw = await token.balanceOf(accountAddress);
const symbol = await token.symbol();
return {
balance: balanceRaw*10**(-tokenDecimals),
symbol: symbol,
};
}
} catch (error) {
console.log ('The getBalanceAndSymbol function had an error!');
console.log (error)
return false;
}
}
Example #6
Source File: contracts.jsx From semaphore_auth with MIT License | 6 votes |
ProofOfBurn = () => {
const data = useProofOfBurnData()
return data.isLoaded ? (
<div className='box has-background-light'>
<div className='content'>
<strong>Group managed by contract</strong> <small>{data.address}</small>
</div>
<nav className='level'>
<div className='level-item has-text-centered'>
<div>
<p className='heading'>Members in the group</p>
<p className='title is-4'>{data.commitments}</p>
</div>
</div>
<div className='level-item has-text-centered'>
<div>
<p className='heading'>Registration Fee</p>
<p className='title is-4'>
{ethers.utils.formatEther(data.registrationFee)} ETH
</p>
</div>
</div>
</nav>
</div>
) : (
<p>Waiting contract data...</p>
)
}
Example #7
Source File: perpetual_finance.route.js From gateway-api with Apache License 2.0 | 6 votes |
router.post('/receipt', async (req, res) => {
/*
POST: /receipt
x-www-form-urlencoded: {
txHash:{{txHash}}
}
*/
const initTime = Date.now();
const paramData = getParamData(req.body);
const txHash = paramData.txHash;
const txReceipt = await perpFi.provider.getTransactionReceipt(txHash);
const receipt = {};
const confirmed = txReceipt && txReceipt.blockNumber ? true : false;
if (txReceipt !== null) {
receipt.gasUsed = ethers.utils.formatEther(txReceipt.gasUsed);
receipt.blockNumber = txReceipt.blockNumber;
receipt.confirmations = txReceipt.confirmations;
receipt.status = txReceipt.status;
}
logger.info(`eth.route - Get TX Receipt: ${txHash}`, {
message: JSON.stringify(receipt),
});
res.status(200).json({
network: perpFi.network,
timestamp: initTime,
latency: latency(initTime, Date.now()),
txHash: txHash,
confirmed: confirmed,
receipt: receipt,
});
return txReceipt;
});
Example #8
Source File: path.js From web3-exchanges with MIT License | 6 votes |
minReserveRequirements = ({ reserves, min, token, token0, token1, decimals }) => {
if(token0.toLowerCase() == token.toLowerCase()) {
return reserves[0].gte(ethers.utils.parseUnits(min.toString(), decimals))
} else if (token1.toLowerCase() == token.toLowerCase()) {
return reserves[1].gte(ethers.utils.parseUnits(min.toString(), decimals))
} else {
return false
}
}
Example #9
Source File: Transaction.js From web3-wallets with MIT License | 6 votes |
static bigNumberify(value, blockchain) {
if (typeof value === 'number') {
return ethers.utils.parseUnits(value.toString(), CONSTANTS[blockchain].DECIMALS)
} else if (value && value.toString) {
return ethers.BigNumber.from(value.toString())
} else {
return value
}
}
Example #10
Source File: sc.interaction.js From Artion-Client with GNU General Public License v3.0 | 6 votes |
useContract = () => {
const { chainId } = useWeb3React();
const loadContract = useCallback(
async (address, abi) => {
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
return new ethers.Contract(address, abi, signer);
},
[chainId]
);
const getAccountBalance = useCallback(
async address => {
const provider = new ethers.providers.Web3Provider(window.ethereum);
let balance = await provider.getBalance(address);
balance = ethers.utils.formatEther(balance);
return balance;
},
[chainId]
);
return { loadContract, getAccountBalance };
}
Example #11
Source File: Dapp.js From hardhat-boilerplate with MIT License | 6 votes |
async _initializeEthers() {
// We first initialize ethers by creating a provider using window.ethereum
this._provider = new ethers.providers.Web3Provider(window.ethereum);
// Then, we initialize the contract using that provider and the token's
// artifact. You can do this same thing with your contracts.
this._token = new ethers.Contract(
contractAddress.Token,
TokenArtifact.abi,
this._provider.getSigner(0)
);
}
Example #12
Source File: Crypto.js From dshop with MIT License | 6 votes |
waitForAllowance = ({ wallet, marketplace, amount, token }) => {
return new Promise((resolve, reject) => {
wallet.signer.getAddress().then((address) => {
async function checkAllowance() {
try {
const decimals = await token.contract.decimals()
const allowance = await token.contract.allowance(
address,
marketplace.address
)
// TODO: formatUnits returns string, Evaluate doing
// parseFloat before the comparison
const allowanceEth = ethers.utils.formatUnits(allowance, decimals)
if (allowanceEth >= amount) {
resolve()
} else {
setTimeout(checkAllowance, 5000)
}
} catch (err) {
reject(err)
}
}
checkAllowance()
})
})
}
Example #13
Source File: index.js From uniswap-v1-frontend with GNU General Public License v3.0 | 5 votes |
GAS_MARGIN = ethers.utils.bigNumberify(1000)
Example #14
Source File: index.js From acy-dex-interface with MIT License | 5 votes |
export function useAllPositions(chainId, library) {
const count = 1000
const query = gql(`{
aggregatedTradeOpens(
first: ${count}
) {
account
initialPosition{
indexToken
collateralToken
isLong
sizeDelta
}
increaseList {
sizeDelta
}
decreaseList {
sizeDelta
}
}
}`)
const [res, setRes] = useState()
useEffect(() => {
nissohGraphClient.query({ query }).then(setRes).catch(console.warn)
}, [setRes, query])
const key = res ? `allPositions${count}__` : false
const { data: positions = [] } = useSWR(key, async () => {
const provider = getProvider(library, chainId)
const vaultAddress = getContract(chainId, "Vault")
const contract = new ethers.Contract(vaultAddress, Vault.abi, provider)
const ret = await Promise.all(res.data.aggregatedTradeOpens.map(async dataItem => {
try {
const { indexToken, collateralToken, isLong } = dataItem.initialPosition
const positionData = await contract.getPosition(dataItem.account, collateralToken, indexToken, isLong)
const position = {
size: bigNumberify(positionData[0]),
collateral: bigNumberify(positionData[1]),
entryFundingRate: bigNumberify(positionData[3]),
account: dataItem.account
}
position.fundingFee = await contract.getFundingFee(collateralToken, position.size, position.entryFundingRate)
position.marginFee = position.size.div(1000)
position.fee = position.fundingFee.add(position.marginFee)
const THRESHOLD = 5000
const collateralDiffPercent = position.fee.mul(10000).div(position.collateral)
position.danger = collateralDiffPercent.gt(THRESHOLD)
return position
} catch (ex) {
console.error(ex)
}
}))
return ret.filter(Boolean)
})
return positions
}
Example #15
Source File: LiquidityFunctions.js From Alternative-Uniswap-Interface with GNU General Public License v3.0 | 5 votes |
// Function used to get a quote of the liquidity addition
// `address1` - An Ethereum address of the coin to recieve (either a token or AUT)
// `address2` - An Ethereum address of the coin to recieve (either a token or AUT)
// `amountA_desired` - The prefered value of the first token that the user would like to deploy as liquidity
// `amountB_desired` - The prefered value of the second token that the user would like to deploy as liquidity
// `factory` - The current factory
// `signer` - The current signer
async function quoteMintLiquidity(
address1,
address2,
amountA,
amountB,
factory,
signer
){
const MINIMUM_LIQUIDITY = 1000;
let _reserveA = 0;
let _reserveB = 0;
let totalSupply = 0;
[_reserveA, _reserveB, totalSupply] = await factory.getPair(address1, address2).then(async (pairAddress) => {
if (pairAddress !== '0x0000000000000000000000000000000000000000'){
const pair = new Contract(pairAddress, PAIR.abi, signer);
const reservesRaw = await fetchReserves(address1, address2, pair, signer); // Returns the reserves already formated as ethers
const reserveA = reservesRaw[0];
const reserveB = reservesRaw[1];
const _totalSupply = await pair.totalSupply();
const totalSupply = Number(ethers.utils.formatEther(_totalSupply));
return [reserveA, reserveB, totalSupply]
} else {
return [0,0,0]
}
});
const token1 = new Contract(address1, ERC20.abi, signer);
const token2 = new Contract(address2, ERC20.abi, signer);
// Need to do all this decimals work to account for 0 decimal numbers
const token1Decimals = await getDecimals(token1);
const token2Decimals = await getDecimals(token2);
const valueA = amountA*(10**token1Decimals);
const valueB = amountB*(10**token2Decimals);
const reserveA = _reserveA*(10**token1Decimals);
const reserveB = _reserveB*(10**token2Decimals);
if (totalSupply == 0){
return Math.sqrt(((valueA * valueB)-MINIMUM_LIQUIDITY))*10**(-18);
};
return (
Math.min(valueA*totalSupply/reserveA, valueB*totalSupply/reserveB)
);
}
Example #16
Source File: index.js From semaphore_auth with MIT License | 5 votes |
getLibrary = provider => {
const library = new ethers.providers.Web3Provider(provider)
return library
}
Example #17
Source File: perpetual_finance.route.js From gateway-api with Apache License 2.0 | 5 votes |
router.post('/balances', async (req, res) => {
/*
POST: /balances
x-www-form-urlencoded: {
privateKey:{{privateKey}}
}
*/
const initTime = Date.now();
const paramData = getParamData(req.body);
const privateKey = paramData.privateKey;
let wallet;
try {
wallet = new ethers.Wallet(privateKey, perpFi.provider);
} catch (err) {
let reason;
err.reason ? (reason = err.reason) : (reason = 'Error getting wallet');
res.status(500).json({
error: reason,
message: err,
});
return;
}
const balances = {};
balances['XDAI'] = await perpFi.getXdaiBalance(wallet);
balances['USDC'] = await perpFi.getUSDCBalance(wallet);
try {
res.status(200).json({
network: perpFi.network,
timestamp: initTime,
latency: latency(initTime, Date.now()),
balances: balances,
});
} catch (err) {
let reason;
err.reason
? (reason = err.reason)
: (reason = statusMessages.operation_error);
res.status(500).json({
error: reason,
message: err,
});
}
});