@ethersproject/providers#TransactionResponse TypeScript Examples
The following examples show how to use
@ethersproject/providers#TransactionResponse.
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: hooks.tsx From sybil-interface with GNU General Public License v3.0 | 6 votes |
// helper that can take a ethers library transaction response and add it to the list of transactions
export function useTransactionAdder(): (response: TransactionResponse, customData?: CustomData) => void {
const { chainId, account } = useActiveWeb3React()
const dispatch = useDispatch<AppDispatch>()
return useCallback(
(response: TransactionResponse, { summary, approval, claim }: CustomData = {}) => {
if (!account) return
if (!chainId) return
const { hash } = response
if (!hash) {
throw Error('No transaction hash found.')
}
dispatch(addTransaction({ hash, from: account, chainId, approval, summary, claim }))
},
[dispatch, chainId, account]
)
}
Example #2
Source File: hooks.tsx From glide-frontend with GNU General Public License v3.0 | 6 votes |
// helper that can take a ethers library transaction response and add it to the list of transactions
export function useTransactionAdder(): (
response: TransactionResponse,
customData?: {
summary?: string
approval?: { tokenAddress: string; spender: string }
claim?: { recipient: string }
},
) => void {
const { chainId, account } = useActiveWeb3React()
const dispatch = useDispatch<AppDispatch>()
return useCallback(
(
response: TransactionResponse,
{
summary,
approval,
claim,
}: { summary?: string; claim?: { recipient: string }; approval?: { tokenAddress: string; spender: string } } = {},
) => {
if (!account) return
if (!chainId) return
const { hash } = response
if (!hash) {
throw Error('No transaction hash found.')
}
dispatch(addTransaction({ hash, from: account, chainId, approval, summary, claim }))
},
[dispatch, chainId, account],
)
}
Example #3
Source File: hooks.ts From forward.swaps with GNU General Public License v3.0 | 6 votes |
export function useDelegateCallback(): (delegatee: string | undefined) => undefined | Promise<string> {
const { account, chainId, library } = useActiveWeb3React()
const addTransaction = useTransactionAdder()
const uniContract = useUniContract()
return useCallback(
(delegatee: string | undefined) => {
if (!library || !chainId || !account || !isAddress(delegatee ?? '')) return undefined
const args = [delegatee]
if (!uniContract) throw new Error('No UNI Contract!')
return uniContract.estimateGas.delegate(...args, {}).then(estimatedGasLimit => {
return uniContract
.delegate(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) })
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Delegated votes`
})
return response.hash
})
})
},
[account, addTransaction, chainId, library, uniContract]
)
}
Example #4
Source File: setup.ts From integration-tests with MIT License | 6 votes |
waitForWithdrawalTypeTransaction = async (
l2OriginatingTx: Promise<TransactionResponse>,
watcher: Watcher,
l1Provider: JsonRpcProvider,
l2Provider: JsonRpcProvider
): Promise<CrossDomainMessagePair> => {
const res = await l2OriginatingTx
await res.wait()
const l2tx = await l2Provider.getTransaction(res.hash)
const l2receipt = await l2Provider.getTransactionReceipt(res.hash)
const [l2ToL1XDomainMsgHash] = await watcher.getMessageHashesFromL2Tx(
res.hash
)
const l1receipt = (await watcher.getL1TransactionReceipt(
l2ToL1XDomainMsgHash
)) as TransactionReceipt
const l1tx = await l1Provider.getTransaction(l1receipt.transactionHash)
return {
l2tx,
l2receipt,
l1tx,
l1receipt,
}
}
Example #5
Source File: hooks.tsx From dyp with Do What The F*ck You Want To Public License | 6 votes |
// helper that can take a ethers library transaction response and add it to the list of transactions
export function useTransactionAdder(): (
response: TransactionResponse,
customData?: { summary?: string; approval?: { tokenAddress: string; spender: string }; claim?: { recipient: string } }
) => void {
const { chainId, account } = useActiveWeb3React()
const dispatch = useDispatch<AppDispatch>()
return useCallback(
(
response: TransactionResponse,
{
summary,
approval,
claim
}: { summary?: string; claim?: { recipient: string }; approval?: { tokenAddress: string; spender: string } } = {}
) => {
if (!account) return
if (!chainId) return
const { hash } = response
if (!hash) {
throw Error('No transaction hash found.')
}
dispatch(addTransaction({ hash, from: account, chainId, approval, summary, claim }))
},
[dispatch, chainId, account]
)
}
Example #6
Source File: index.ts From ccip-read with MIT License | 6 votes |
async sendTransaction(request: Deferrable<TransactionRequest>): Promise<TransactionResponse> {
let transaction = await resolveProperties(request);
// gasLimit, if set, applies to the final transaction; unset it for the preflight
const gasLimit = transaction.gasLimit;
delete transaction.gasLimit;
({ transaction } = await handleCall(this.provider, { transaction, blockTag: 'latest' }));
// Restore the original gasLimit, if any
transaction.gasLimit = gasLimit;
return this.parent.sendTransaction(transaction);
}
Example #7
Source File: hooks.tsx From goose-frontend-amm with GNU General Public License v3.0 | 6 votes |
// helper that can take a ethers library transaction response and add it to the list of transactions
export function useTransactionAdder(): (
response: TransactionResponse,
customData?: { summary?: string; approval?: { tokenAddress: string; spender: string } }
) => void {
const { chainId, account } = useActiveWeb3React()
const dispatch = useDispatch<AppDispatch>()
return useCallback(
(
response: TransactionResponse,
{ summary, approval }: { summary?: string; approval?: { tokenAddress: string; spender: string } } = {}
) => {
if (!account) return
if (!chainId) return
const { hash } = response
if (!hash) {
throw Error('No transaction hash found.')
}
dispatch(addTransaction({ hash, from: account, chainId, approval, summary }))
},
[dispatch, chainId, account]
)
}
Example #8
Source File: hooks.tsx From cheeseswap-interface with GNU General Public License v3.0 | 6 votes |
// helper that can take a ethers library transaction response and add it to the list of transactions
export function useTransactionAdder(): (
response: TransactionResponse,
customData?: { summary?: string; approval?: { tokenAddress: string; spender: string } }
) => void {
const { chainId, account } = useActiveWeb3React()
const dispatch = useDispatch<AppDispatch>()
return useCallback(
(
response: TransactionResponse,
{ summary, approval }: { summary?: string; approval?: { tokenAddress: string; spender: string } } = {}
) => {
if (!account) return
if (!chainId) return
const { hash } = response
if (!hash) {
throw Error('No transaction hash found.')
}
dispatch(addTransaction({ hash, from: account, chainId, approval, summary }))
},
[dispatch, chainId, account]
)
}
Example #9
Source File: hooks.ts From sybil-interface with GNU General Public License v3.0 | 6 votes |
export function useDelegateCallback(): (delegatee: string | undefined) => undefined | Promise<string> {
const { account, chainId, library } = useActiveWeb3React()
const addTransaction = useTransactionAdder()
const govTokenContract = useGovTokenContract()
return useCallback(
(delegatee: string | undefined) => {
if (!library || !chainId || !account || !isAddress(delegatee ?? '')) return undefined
const args = [delegatee]
if (!govTokenContract) throw new Error('No Governance Contract!')
return govTokenContract.estimateGas.delegate(...args, {}).then((estimatedGasLimit) => {
return govTokenContract
.delegate(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) })
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Delegated votes`,
})
return response.hash
})
})
},
[account, addTransaction, chainId, library, govTokenContract]
)
}
Example #10
Source File: hooks.ts From interface-v2 with GNU General Public License v3.0 | 6 votes |
export function useVoteCallback(): {
voteCallback: (
proposalId: string | undefined,
support: boolean,
) => undefined | Promise<string>;
} {
const { account } = useActiveWeb3React();
const govContract = useGovernanceContract();
const addTransaction = useTransactionAdder();
const voteCallback = useCallback(
(proposalId: string | undefined, support: boolean) => {
if (!account || !govContract || !proposalId) return;
const args = [proposalId, support];
return govContract.estimateGas
.castVote(...args, {})
.then((estimatedGasLimit) => {
return govContract
.castVote(...args, {
value: null,
gasLimit: calculateGasMargin(estimatedGasLimit),
})
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Voted ${
support ? 'for ' : 'against'
} proposal ${proposalId}`,
});
return response.hash;
});
});
},
[account, addTransaction, govContract],
);
return { voteCallback };
}
Example #11
Source File: transactions.ts From pownft-miner with Apache License 2.0 | 6 votes |
export async function mineAtom(instance: Contract, targetAtom: TargetAtom, gasPrice: BigNumber, dryRun: boolean) : Promise<TransactionResponse | false> {
const value = targetAtom.cost;
const prefix = dryRun ? '[DRY RUN] ' : '';
console.log(`${prefix}Issuing tx to mine atom ${targetAtom.tokenId} for ${formatEther(value)} eth using gas ${formatUnits(gasPrice, 'gwei')} using nonce ${targetAtom.nonce.toString()}`);
// this will simulate the tx on chain, if anyone has mined a block it will fail with a "revert: difficulty" message
const gasLimit = await instance.estimateGas.mine(targetAtom.nonce, {value, gasPrice});
if (dryRun) {
return false;
} else {
return instance.mine(targetAtom.nonce, {value, gasPrice, gasLimit});
}
}
Example #12
Source File: hooks.ts From luaswap-interface with GNU General Public License v3.0 | 6 votes |
export function useClaimCallback(
account: string | null | undefined
): {
claimCallback: () => Promise<string>
} {
// get claim data for this account
const { library, chainId } = useActiveWeb3React()
const claimData = useUserClaimData(account)
// used for popup summary
const unClaimedAmount: TokenAmount | undefined = useUserUnclaimedAmount(account)
const addTransaction = useTransactionAdder()
const distributorContract = useMerkleDistributorContract()
const claimCallback = async function() {
if (!claimData || !account || !library || !chainId || !distributorContract) return
const args = [claimData.index, account, claimData.amount, claimData.proof]
return distributorContract.estimateGas['claim'](...args, {}).then(estimatedGasLimit => {
return distributorContract
.claim(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) })
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Claimed ${unClaimedAmount?.toSignificant(4)} UNI`,
claim: { recipient: account }
})
return response.hash
})
})
}
return { claimCallback }
}
Example #13
Source File: hooks.tsx From cuiswap with GNU General Public License v3.0 | 6 votes |
// helper that can take a ethers library transaction response and add it to the list of transactions
export function useTransactionAdder(): (
response: TransactionResponse,
customData?: { summary?: string; approval?: { tokenAddress: string; spender: string } }
) => void {
const { chainId, account } = useActiveWeb3React()
const dispatch = useDispatch<AppDispatch>()
return useCallback(
(
response: TransactionResponse,
{ summary, approval }: { summary?: string; approval?: { tokenAddress: string; spender: string } } = {}
) => {
if (!account) return
if (!chainId) return
const { hash } = response
if (!hash) {
throw Error('No transaction hash found.')
}
dispatch(addTransaction({ hash, from: account, chainId, approval, summary }))
},
[dispatch, chainId, account]
)
}
Example #14
Source File: hooks.ts From luaswap-interface with GNU General Public License v3.0 | 6 votes |
export function useDelegateCallback(): (delegatee: string | undefined) => undefined | Promise<string> {
const { account, chainId, library } = useActiveWeb3React()
const addTransaction = useTransactionAdder()
const uniContract = useUniContract()
return useCallback(
(delegatee: string | undefined) => {
if (!library || !chainId || !account || !isAddress(delegatee ?? '')) return undefined
const args = [delegatee]
if (!uniContract) throw new Error('No UNI Contract!')
return uniContract.estimateGas.delegate(...args, {}).then(estimatedGasLimit => {
return uniContract
.delegate(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) })
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Delegated votes`
})
return response.hash
})
})
},
[account, addTransaction, chainId, library, uniContract]
)
}
Example #15
Source File: hooks.ts From interface-v2 with GNU General Public License v3.0 | 5 votes |
export function useClaimCallback(
account: string | null | undefined,
): {
claimCallback: () => Promise<string>;
} {
// get claim data for this account
const { library, chainId } = useActiveWeb3React();
const claimData = useUserClaimData(account);
// used for popup summary
const unClaimedAmount: TokenAmount | undefined = useUserUnclaimedAmount(
account,
);
const addTransaction = useTransactionAdder();
const distributorContract = useMerkleDistributorContract();
const claimCallback = async function() {
if (!claimData || !account || !library || !chainId || !distributorContract)
return;
const args = [claimData.index, account, claimData.amount, claimData.proof];
return distributorContract.estimateGas['claim'](...args, {}).then(
(estimatedGasLimit) => {
return distributorContract
.claim(...args, {
value: null,
gasLimit: calculateGasMargin(estimatedGasLimit),
})
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Claimed ${formatTokenAmount(unClaimedAmount)} QUICK`,
claim: { recipient: account },
});
return response.hash;
});
},
);
};
return { claimCallback };
}
Example #16
Source File: useApproveCallback.ts From cuiswap with GNU General Public License v3.0 | 5 votes |
// returns a variable indicating the state of the approval and a function which approves if necessary or early returns
export function useApproveCallback(
amountToApprove?: CurrencyAmount,
spender?: string
): [ApprovalState, () => Promise<void>] {
const { account } = useActiveWeb3React()
const token = amountToApprove instanceof TokenAmount ? amountToApprove.token : undefined
const currentAllowance = useTokenAllowance(token, account ?? undefined, spender)
const pendingApproval = useHasPendingApproval(token?.address, spender)
// check the current approval status
const approvalState: ApprovalState = useMemo(() => {
if (!amountToApprove || !spender) return ApprovalState.UNKNOWN
if (amountToApprove.currency === ETHER) return ApprovalState.APPROVED
// we might not have enough data to know whether or not we need to approve
if (!currentAllowance) return ApprovalState.UNKNOWN
// amountToApprove will be defined if currentAllowance is
return currentAllowance.lessThan(amountToApprove)
? pendingApproval
? ApprovalState.PENDING
: ApprovalState.NOT_APPROVED
: ApprovalState.APPROVED
}, [amountToApprove, currentAllowance, pendingApproval, spender])
const tokenContract = useTokenContract(token?.address)
const addTransaction = useTransactionAdder()
const approve = useCallback(async (): Promise<void> => {
if (approvalState !== ApprovalState.NOT_APPROVED) {
console.error('approve was called unnecessarily')
return
}
if (!token) {
console.error('no token')
return
}
if (!tokenContract) {
console.error('tokenContract is null')
return
}
if (!amountToApprove) {
console.error('missing amount to approve')
return
}
if (!spender) {
console.error('no spender')
return
}
let useExact = false
const estimatedGas = await tokenContract.estimateGas.approve(spender, MaxUint256).catch(() => {
// general fallback for tokens who restrict approval amounts
useExact = true
return tokenContract.estimateGas.approve(spender, amountToApprove.raw.toString())
})
return tokenContract
.approve(spender, useExact ? amountToApprove.raw.toString() : MaxUint256, {
gasLimit: calculateGasMargin(estimatedGas)
})
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: 'Approve ' + amountToApprove.currency.symbol,
approval: { tokenAddress: token.address, spender: spender }
})
})
.catch((error: Error) => {
console.debug('Failed to approve token', error)
throw error
})
}, [approvalState, token, tokenContract, amountToApprove, spender, addTransaction])
return [approvalState, approve]
}
Example #17
Source File: hooks.tsx From limit-orders-lib with GNU General Public License v3.0 | 5 votes |
// helper that can take a ethers library transaction response and add it to the list of transactions
export function useTransactionAdder(): (
response: TransactionResponse,
customData?: {
summary?: string;
order?: Order;
type: TransactionType;
approval?: { tokenAddress: string; spender: string };
}
) => void {
const { chainId, account } = useWeb3();
const dispatch = useDispatch<AppDispatch>();
return useCallback(
(
response: TransactionResponse,
{
summary,
type,
order,
approval,
}: {
summary?: string;
order?: Order;
type: TransactionType;
approval?: { tokenAddress: string; spender: string };
} = { type: "submission" }
) => {
if (!account) return;
if (!chainId) return;
const { hash } = response;
if (!hash) {
throw Error("No transaction hash found.");
}
dispatch(
addTransaction({
hash,
from: account,
order,
chainId,
type,
approval,
summary,
})
);
},
[dispatch, chainId, account]
);
}
Example #18
Source File: index.ts From pownft-miner with Apache License 2.0 | 5 votes |
async function main() {
const { provider, signer, numCores, chunkSize, gasLimit, dryRun } = loadConfig();
const address = await signer.getAddress();
console.log(`Miner configured with address ${address} using ${numCores} cores`);
if (dryRun) {
console.log("Running in dry run mode, no transactions will be submitted")
}
// guard, use a read-only signer while mining
const voidSigner = new VoidSigner(address, provider);
const instance = powNftContract(voidSigner);
const targetAtom = await mineNextAtom({
numThreads: numCores,
provider,
instance,
signerAddress: address,
chunkSize,
});
console.log('Found atom!! Trying to submit tx...');
const gasPrices = await getGasPrices();
if (BigNumber.from(gasPrices.rapid).gt(gasLimit)) {
throw Error(`Gas too expensive, the max is ${formatUnits(gasLimit, 'gwei')}! Not going to mine`);
}
console.log(`Gas price ${formatUnits(gasPrices.rapid, 'gwei')} is below the max of ${formatUnits(gasLimit, 'gwei')}`);
if (dryRun) {
console.log('Dry run mode, estimating gas but will not issue tx');
const tx = await mineAtom(instance, targetAtom, BigNumber.from(gasPrices.rapid), dryRun);
} else {
// use the real signer
const liveInstance = powNftContract(signer);
const tx = (await mineAtom(liveInstance, targetAtom, BigNumber.from(gasPrices.rapid), dryRun)) as TransactionResponse;
console.log(`Submitted transaction ${tx.hash}`);
const txReceipt = await tx.wait();
console.log('Transaction mined!');
}
}
Example #19
Source File: useApproveCallback.ts From pancakeswap-testnet with GNU General Public License v3.0 | 5 votes |
// returns a variable indicating the state of the approval and a function which approves if necessary or early returns
export function useApproveCallback(
amountToApprove?: CurrencyAmount,
spender?: string
): [ApprovalState, () => Promise<void>] {
const { account } = useActiveWeb3React()
const token = amountToApprove instanceof TokenAmount ? amountToApprove.token : undefined
const currentAllowance = useTokenAllowance(token, account ?? undefined, spender)
const pendingApproval = useHasPendingApproval(token?.address, spender)
// check the current approval status
const approvalState: ApprovalState = useMemo(() => {
if (!amountToApprove || !spender) return ApprovalState.UNKNOWN
if (amountToApprove.currency === ETHER) return ApprovalState.APPROVED
// we might not have enough data to know whether or not we need to approve
if (!currentAllowance) return ApprovalState.UNKNOWN
// amountToApprove will be defined if currentAllowance is
return currentAllowance.lessThan(amountToApprove)
? pendingApproval
? ApprovalState.PENDING
: ApprovalState.NOT_APPROVED
: ApprovalState.APPROVED
}, [amountToApprove, currentAllowance, pendingApproval, spender])
const tokenContract = useTokenContract(token?.address)
const addTransaction = useTransactionAdder()
const approve = useCallback(async (): Promise<void> => {
if (approvalState !== ApprovalState.NOT_APPROVED) {
console.error('approve was called unnecessarily')
return
}
if (!token) {
console.error('no token')
return
}
if (!tokenContract) {
console.error('tokenContract is null')
return
}
if (!amountToApprove) {
console.error('missing amount to approve')
return
}
if (!spender) {
console.error('no spender')
return
}
let useExact = false
const estimatedGas = await tokenContract.estimateGas.approve(spender, MaxUint256).catch(() => {
// general fallback for tokens who restrict approval amounts
useExact = true
return tokenContract.estimateGas.approve(spender, amountToApprove.raw.toString())
})
// eslint-disable-next-line consistent-return
return tokenContract
.approve(spender, useExact ? amountToApprove.raw.toString() : MaxUint256, {
gasLimit: calculateGasMargin(estimatedGas),
})
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Approve ${amountToApprove.currency.symbol}`,
approval: { tokenAddress: token.address, spender },
})
})
.catch((error: Error) => {
console.error('Failed to approve token', error)
throw error
})
}, [approvalState, token, tokenContract, amountToApprove, spender, addTransaction])
return [approvalState, approve]
}
Example #20
Source File: DeploymentsManager.ts From hardhat-deploy with MIT License | 5 votes |
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
public async onPendingTx(
tx: TransactionResponse,
name?: string,
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
deployment?: any
): Promise<TransactionResponse> {
if (
this.db.writeDeploymentsToFiles &&
this.network.saveDeployments &&
this.db.savePendingTx
) {
const deployFolderPath = path.join(
this.deploymentsPath,
this.deploymentFolder()
);
// console.log("tx", tx.hash);
const pendingTxPath = path.join(deployFolderPath, '.pendingTransactions');
fs.ensureDirSync(deployFolderPath);
const rawTx = tx.raw;
const decoded = tx.raw
? undefined
: {
from: tx.from,
gasPrice: tx.gasPrice?.toString(),
maxFeePerGas: tx.maxFeePerGas?.toString(),
maxPriorityFeePerGas: tx.maxPriorityFeePerGas?.toString(),
gasLimit: tx.gasLimit.toString(),
to: tx.to,
value: tx.value.toString(),
nonce: tx.nonce,
data: tx.data,
r: tx.r,
s: tx.s,
v: tx.v,
// creates: tx.creates, // TODO test
chainId: tx.chainId,
};
this.db.pendingTransactions[tx.hash] = name
? {name, deployment, rawTx, decoded}
: {rawTx, decoded};
fs.writeFileSync(
pendingTxPath,
JSON.stringify(this.db.pendingTransactions, null, ' ')
);
// await new Promise(r => setTimeout(r, 20000));
const wait = tx.wait.bind(tx);
tx.wait = async (confirmations?: number) => {
const receipt = await wait(confirmations);
// console.log("checking pending tx...");
delete this.db.pendingTransactions[tx.hash];
if (Object.keys(this.db.pendingTransactions).length === 0) {
fs.removeSync(pendingTxPath);
} else {
fs.writeFileSync(
pendingTxPath,
JSON.stringify(this.db.pendingTransactions, null, ' ')
);
}
this.db.gasUsed = this.db.gasUsed.add(receipt.gasUsed);
return receipt;
};
} else {
const wait = tx.wait.bind(tx);
tx.wait = async (confirmations?: number) => {
const receipt = await wait(confirmations);
this.db.gasUsed = this.db.gasUsed.add(receipt.gasUsed);
return receipt;
};
}
return tx;
}
Example #21
Source File: useApproveCallback.ts From panther-frontend-dex with GNU General Public License v3.0 | 5 votes |
// returns a variable indicating the state of the approval and a function which approves if necessary or early returns
export function useApproveCallback(
amountToApprove?: CurrencyAmount,
spender?: string
): [ApprovalState, () => Promise<void>] {
const { account } = useActiveWeb3React()
const token = amountToApprove instanceof TokenAmount ? amountToApprove.token : undefined
const currentAllowance = useTokenAllowance(token, account ?? undefined, spender)
const pendingApproval = useHasPendingApproval(token?.address, spender)
// check the current approval status
const approvalState: ApprovalState = useMemo(() => {
if (!amountToApprove || !spender) return ApprovalState.UNKNOWN
if (amountToApprove.currency === ETHER) return ApprovalState.APPROVED
// we might not have enough data to know whether or not we need to approve
if (!currentAllowance) return ApprovalState.UNKNOWN
// amountToApprove will be defined if currentAllowance is
return currentAllowance.lessThan(amountToApprove)
? pendingApproval
? ApprovalState.PENDING
: ApprovalState.NOT_APPROVED
: ApprovalState.APPROVED
}, [amountToApprove, currentAllowance, pendingApproval, spender])
const tokenContract = useTokenContract(token?.address)
const addTransaction = useTransactionAdder()
const approve = useCallback(async (): Promise<void> => {
if (approvalState !== ApprovalState.NOT_APPROVED) {
console.error('approve was called unnecessarily')
return
}
if (!token) {
console.error('no token')
return
}
if (!tokenContract) {
console.error('tokenContract is null')
return
}
if (!amountToApprove) {
console.error('missing amount to approve')
return
}
if (!spender) {
console.error('no spender')
return
}
let useExact = false
const estimatedGas = await tokenContract.estimateGas.approve(spender, MaxUint256).catch(() => {
// general fallback for tokens who restrict approval amounts
useExact = true
return tokenContract.estimateGas.approve(spender, amountToApprove.raw.toString())
})
// eslint-disable-next-line consistent-return
return tokenContract
.approve(spender, useExact ? amountToApprove.raw.toString() : MaxUint256, {
gasLimit: calculateGasMargin(estimatedGas),
})
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Approve ${amountToApprove.currency.symbol}`,
approval: { tokenAddress: token.address, spender },
})
})
.catch((error: Error) => {
console.error('Failed to approve token', error)
throw error
})
}, [approvalState, token, tokenContract, amountToApprove, spender, addTransaction])
return [approvalState, approve]
}
Example #22
Source File: useApproveCallback.ts From pancake-swap-exchange-testnet with GNU General Public License v3.0 | 5 votes |
// returns a variable indicating the state of the approval and a function which approves if necessary or early returns
export function useApproveCallback(
amountToApprove?: CurrencyAmount,
spender?: string
): [ApprovalState, () => Promise<void>] {
const { account } = useActiveWeb3React()
const token = amountToApprove instanceof TokenAmount ? amountToApprove.token : undefined
const currentAllowance = useTokenAllowance(token, account ?? undefined, spender)
const pendingApproval = useHasPendingApproval(token?.address, spender)
// check the current approval status
const approvalState: ApprovalState = useMemo(() => {
if (!amountToApprove || !spender) return ApprovalState.UNKNOWN
if (amountToApprove.currency === ETHER) return ApprovalState.APPROVED
// we might not have enough data to know whether or not we need to approve
if (!currentAllowance) return ApprovalState.UNKNOWN
// amountToApprove will be defined if currentAllowance is
return currentAllowance.lessThan(amountToApprove)
? pendingApproval
? ApprovalState.PENDING
: ApprovalState.NOT_APPROVED
: ApprovalState.APPROVED
}, [amountToApprove, currentAllowance, pendingApproval, spender])
const tokenContract = useTokenContract(token?.address)
const addTransaction = useTransactionAdder()
const approve = useCallback(async (): Promise<void> => {
if (approvalState !== ApprovalState.NOT_APPROVED) {
console.error('approve was called unnecessarily')
return
}
if (!token) {
console.error('no token')
return
}
if (!tokenContract) {
console.error('tokenContract is null')
return
}
if (!amountToApprove) {
console.error('missing amount to approve')
return
}
if (!spender) {
console.error('no spender')
return
}
let useExact = false
const estimatedGas = await tokenContract.estimateGas.approve(spender, MaxUint256).catch(() => {
// general fallback for tokens who restrict approval amounts
useExact = true
return tokenContract.estimateGas.approve(spender, amountToApprove.raw.toString())
})
// eslint-disable-next-line consistent-return
return tokenContract
.approve(spender, useExact ? amountToApprove.raw.toString() : MaxUint256, {
gasLimit: calculateGasMargin(estimatedGas),
})
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Approve ${amountToApprove.currency.symbol}`,
approval: { tokenAddress: token.address, spender },
})
})
.catch((error: Error) => {
console.error('Failed to approve token', error)
throw error
})
}, [approvalState, token, tokenContract, amountToApprove, spender, addTransaction])
return [approvalState, approve]
}
Example #23
Source File: useApproveCallback.ts From goose-frontend-amm with GNU General Public License v3.0 | 5 votes |
// returns a variable indicating the state of the approval and a function which approves if necessary or early returns
export function useApproveCallback(
amountToApprove?: CurrencyAmount,
spender?: string
): [ApprovalState, () => Promise<void>] {
const { account } = useActiveWeb3React()
const token = amountToApprove instanceof TokenAmount ? amountToApprove.token : undefined
const currentAllowance = useTokenAllowance(token, account ?? undefined, spender)
const pendingApproval = useHasPendingApproval(token?.address, spender)
// check the current approval status
const approvalState: ApprovalState = useMemo(() => {
if (!amountToApprove || !spender) return ApprovalState.UNKNOWN
if (amountToApprove.currency === ETHER) return ApprovalState.APPROVED
// we might not have enough data to know whether or not we need to approve
if (!currentAllowance) return ApprovalState.UNKNOWN
// amountToApprove will be defined if currentAllowance is
return currentAllowance.lessThan(amountToApprove)
? pendingApproval
? ApprovalState.PENDING
: ApprovalState.NOT_APPROVED
: ApprovalState.APPROVED
}, [amountToApprove, currentAllowance, pendingApproval, spender])
const tokenContract = useTokenContract(token?.address)
const addTransaction = useTransactionAdder()
const approve = useCallback(async (): Promise<void> => {
if (approvalState !== ApprovalState.NOT_APPROVED) {
console.error('approve was called unnecessarily')
return
}
if (!token) {
console.error('no token')
return
}
if (!tokenContract) {
console.error('tokenContract is null')
return
}
if (!amountToApprove) {
console.error('missing amount to approve')
return
}
if (!spender) {
console.error('no spender')
return
}
let useExact = false
const estimatedGas = await tokenContract.estimateGas.approve(spender, MaxUint256).catch(() => {
// general fallback for tokens who restrict approval amounts
useExact = true
return tokenContract.estimateGas.approve(spender, amountToApprove.raw.toString())
})
// eslint-disable-next-line consistent-return
return tokenContract
.approve(spender, useExact ? amountToApprove.raw.toString() : MaxUint256, {
gasLimit: calculateGasMargin(estimatedGas),
})
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Approve ${amountToApprove.currency.symbol}`,
approval: { tokenAddress: token.address, spender },
})
})
.catch((error: Error) => {
console.error('Failed to approve token', error)
throw error
})
}, [approvalState, token, tokenContract, amountToApprove, spender, addTransaction])
return [approvalState, approve]
}
Example #24
Source File: useApproveCallback.ts From luaswap-interface with GNU General Public License v3.0 | 5 votes |
// returns a variable indicating the state of the approval and a function which approves if necessary or early returns
export function useApproveCallback(
amountToApprove?: CurrencyAmount,
spender?: string
): [ApprovalState, () => Promise<void>] {
const { account } = useActiveWeb3React()
const token = amountToApprove instanceof TokenAmount ? amountToApprove.token : undefined
const currentAllowance = useTokenAllowance(token, account ?? undefined, spender)
const pendingApproval = useHasPendingApproval(token?.address, spender)
// check the current approval status
const approvalState: ApprovalState = useMemo(() => {
if (!amountToApprove || !spender) return ApprovalState.UNKNOWN
if (amountToApprove.currency === ETHER || amountToApprove.currency === TOMO) return ApprovalState.APPROVED
// we might not have enough data to know whether or not we need to approve
if (!currentAllowance) return ApprovalState.UNKNOWN
// amountToApprove will be defined if currentAllowance is
return currentAllowance.lessThan(amountToApprove)
? pendingApproval
? ApprovalState.PENDING
: ApprovalState.NOT_APPROVED
: ApprovalState.APPROVED
}, [amountToApprove, currentAllowance, pendingApproval, spender])
const tokenContract = useTokenContract(token?.address)
const addTransaction = useTransactionAdder()
const approve = useCallback(async (): Promise<void> => {
if (approvalState !== ApprovalState.NOT_APPROVED) {
console.error('approve was called unnecessarily')
return
}
if (!token) {
console.error('no token')
return
}
if (!tokenContract) {
console.error('tokenContract is null')
return
}
if (!amountToApprove) {
console.error('missing amount to approve')
return
}
if (!spender) {
console.error('no spender')
return
}
let useExact = false
const estimatedGas = await tokenContract.estimateGas.approve(spender, MaxUint256).catch(() => {
// general fallback for tokens who restrict approval amounts
useExact = true
return tokenContract.estimateGas.approve(spender, amountToApprove.raw.toString())
})
return tokenContract
.approve(spender, useExact ? amountToApprove.raw.toString() : MaxUint256, {
gasLimit: calculateGasMargin(estimatedGas)
})
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: 'Approve ' + amountToApprove.currency.symbol,
approval: { tokenAddress: token.address, spender: spender }
})
})
.catch((error: Error) => {
console.debug('Failed to approve token', error)
throw error
})
}, [approvalState, token, tokenContract, amountToApprove, spender, addTransaction])
return [approvalState, approve]
}
Example #25
Source File: useApproveCallback.ts From mozartfinance-swap-interface with GNU General Public License v3.0 | 5 votes |
// returns a variable indicating the state of the approval and a function which approves if necessary or early returns
export function useApproveCallback(
amountToApprove?: CurrencyAmount,
spender?: string
): [ApprovalState, () => Promise<void>] {
const { account } = useActiveWeb3React()
const token = amountToApprove instanceof TokenAmount ? amountToApprove.token : undefined
const currentAllowance = useTokenAllowance(token, account ?? undefined, spender)
const pendingApproval = useHasPendingApproval(token?.address, spender)
// check the current approval status
const approvalState: ApprovalState = useMemo(() => {
if (!amountToApprove || !spender) return ApprovalState.UNKNOWN
if (amountToApprove.currency === ETHER) return ApprovalState.APPROVED
// we might not have enough data to know whether or not we need to approve
if (!currentAllowance) return ApprovalState.UNKNOWN
// amountToApprove will be defined if currentAllowance is
return currentAllowance.lessThan(amountToApprove)
? pendingApproval
? ApprovalState.PENDING
: ApprovalState.NOT_APPROVED
: ApprovalState.APPROVED
}, [amountToApprove, currentAllowance, pendingApproval, spender])
const tokenContract = useTokenContract(token?.address)
const addTransaction = useTransactionAdder()
const approve = useCallback(async (): Promise<void> => {
if (approvalState !== ApprovalState.NOT_APPROVED) {
console.error('approve was called unnecessarily')
return
}
if (!token) {
console.error('no token')
return
}
if (!tokenContract) {
console.error('tokenContract is null')
return
}
if (!amountToApprove) {
console.error('missing amount to approve')
return
}
if (!spender) {
console.error('no spender')
return
}
let useExact = false
const estimatedGas = await tokenContract.estimateGas.approve(spender, MaxUint256).catch(() => {
// general fallback for tokens who restrict approval amounts
useExact = true
return tokenContract.estimateGas.approve(spender, amountToApprove.raw.toString())
})
// eslint-disable-next-line consistent-return
return tokenContract
.approve(spender, useExact ? amountToApprove.raw.toString() : MaxUint256, {
gasLimit: calculateGasMargin(estimatedGas),
})
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Approve ${amountToApprove.currency.symbol}`,
approval: { tokenAddress: token.address, spender },
})
})
.catch((error: Error) => {
console.error('Failed to approve token', error)
throw error
})
}, [approvalState, token, tokenContract, amountToApprove, spender, addTransaction])
return [approvalState, approve]
}
Example #26
Source File: useApproveCallback.ts From cheeseswap-interface with GNU General Public License v3.0 | 5 votes |
// returns a variable indicating the state of the approval and a function which approves if necessary or early returns
export function useApproveCallback(
amountToApprove?: CurrencyAmount,
spender?: string
): [ApprovalState, () => Promise<void>] {
const { account } = useActiveWeb3React()
const token = amountToApprove instanceof TokenAmount ? amountToApprove.token : undefined
const currentAllowance = useTokenAllowance(token, account ?? undefined, spender)
const pendingApproval = useHasPendingApproval(token?.address, spender)
// check the current approval status
const approvalState: ApprovalState = useMemo(() => {
if (!amountToApprove || !spender) return ApprovalState.UNKNOWN
if (amountToApprove.currency === ETHER) return ApprovalState.APPROVED
// we might not have enough data to know whether or not we need to approve
if (!currentAllowance) return ApprovalState.UNKNOWN
// amountToApprove will be defined if currentAllowance is
return currentAllowance.lessThan(amountToApprove)
? pendingApproval
? ApprovalState.PENDING
: ApprovalState.NOT_APPROVED
: ApprovalState.APPROVED
}, [amountToApprove, currentAllowance, pendingApproval, spender])
const tokenContract = useTokenContract(token?.address)
const addTransaction = useTransactionAdder()
const approve = useCallback(async (): Promise<void> => {
if (approvalState !== ApprovalState.NOT_APPROVED) {
console.error('approve was called unnecessarily')
return
}
if (!token) {
console.error('no token')
return
}
if (!tokenContract) {
console.error('tokenContract is null')
return
}
if (!amountToApprove) {
console.error('missing amount to approve')
return
}
if (!spender) {
console.error('no spender')
return
}
let useExact = false
const estimatedGas = await tokenContract.estimateGas.approve(spender, MaxUint256).catch(() => {
// general fallback for tokens who restrict approval amounts
useExact = true
return tokenContract.estimateGas.approve(spender, amountToApprove.raw.toString())
})
return tokenContract
.approve(spender, useExact ? amountToApprove.raw.toString() : MaxUint256, {
gasLimit: calculateGasMargin(estimatedGas)
})
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: 'Approve ' + amountToApprove.currency.symbol,
approval: { tokenAddress: token.address, spender: spender }
})
})
.catch((error: Error) => {
console.debug('Failed to approve token', error)
throw error
})
}, [approvalState, token, tokenContract, amountToApprove, spender, addTransaction])
return [approvalState, approve]
}
Example #27
Source File: hooks.ts From sybil-interface with GNU General Public License v3.0 | 5 votes |
export function useVoteCallback(): {
voteCallback: (proposalId: string | undefined, support: boolean) => undefined | Promise<string>
} {
const { account } = useActiveWeb3React()
const govContract = useGovernanceContract()
const addTransaction = useTransactionAdder()
const isAaveGov = useIsAave()
const voteCallback = useCallback(
(proposalId: string | undefined, support: boolean) => {
if (!account || !govContract || !proposalId) return
const args = [proposalId, support]
if (isAaveGov) {
return govContract.estimateGas.submitVote(...args, {}).then((estimatedGasLimit) => {
return govContract
.submitVote(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) })
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Voted ${support ? 'for ' : 'against'} proposal ${proposalId}`,
})
return response.hash
})
})
} else {
return govContract.estimateGas.castVote(...args, {}).then((estimatedGasLimit) => {
return govContract
.castVote(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) })
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Voted ${support ? 'for ' : 'against'} proposal ${proposalId}`,
})
return response.hash
})
})
}
},
[account, addTransaction, govContract, isAaveGov]
)
return { voteCallback }
}
Example #28
Source File: hooks.ts From interface-v2 with GNU General Public License v3.0 | 5 votes |
// helper that can take a ethers library transaction response and add it to the list of transactions
export function useTransactionAdder(): (
response: TransactionResponse,
customData?: {
summary?: string;
approval?: { tokenAddress: string; spender: string };
claim?: { recipient: string };
},
) => void {
const { chainId, account } = useActiveWeb3React();
const dispatch = useDispatch<AppDispatch>();
return useCallback(
(
response: TransactionResponse,
{
summary,
approval,
claim,
}: {
summary?: string;
claim?: { recipient: string };
approval?: { tokenAddress: string; spender: string };
} = {},
) => {
if (!account) return;
if (!chainId) return;
const { hash } = response;
if (!hash) {
throw Error('No transaction hash found.');
}
dispatch(
addTransaction({
hash,
from: account,
chainId,
approval,
summary,
claim,
}),
);
},
[dispatch, chainId, account],
);
}
Example #29
Source File: useApproveCallback.ts From forward.swaps with GNU General Public License v3.0 | 4 votes |
// returns a variable indicating the state of the approval and a function which approves if necessary or early returns
export function useApproveCallback(
amountToApprove?: CurrencyAmount,
spender?: string
): [ApprovalState, () => Promise<void>] {
const { account } = useActiveWeb3React()
const token = amountToApprove instanceof TokenAmount ? amountToApprove.token : undefined
const currentAllowance = useTokenAllowance(token, account ?? undefined, spender)
const pendingApproval = useHasPendingApproval(token?.address, spender)
// check the current approval status
const approvalState: ApprovalState = useMemo(() => {
if (!amountToApprove || !spender) return ApprovalState.UNKNOWN
if (amountToApprove.currency === ETHER) return ApprovalState.APPROVED
// we might not have enough data to know whether or not we need to approve
if (!currentAllowance) return ApprovalState.UNKNOWN
// amountToApprove will be defined if currentAllowance is
return currentAllowance.lessThan(amountToApprove)
? pendingApproval
? ApprovalState.PENDING
: ApprovalState.NOT_APPROVED
: ApprovalState.APPROVED
}, [amountToApprove, currentAllowance, pendingApproval, spender])
const tokenContract = useTokenContract(token?.address)
const addTransaction = useTransactionAdder()
const approve = useCallback(async (): Promise<void> => {
try {
if (approvalState !== ApprovalState.NOT_APPROVED) {
console.error('approve was called unnecessarily')
return
}
if (!token) {
console.error('no token')
return
}
if (!tokenContract) {
console.error('tokenContract is null')
return
}
if (!amountToApprove) {
console.error('missing amount to approve')
return
}
if (!spender) {
console.error('no spender')
return
}
let useExact = false
const estimatedGas = await tokenContract.estimateGas.approve(spender, MaxUint256).catch(() => {
// general fallback for tokens who restrict approval amounts
useExact = true
return tokenContract.estimateGas.approve(spender, amountToApprove.raw.toString())
})
let domainData
let tokenPermitOptions1
let permitTx
if (tokenContract.address == DAI_kovan_contract.address) {
if (getPermitClient() == '' || getPermitClient() == 'undefined' || getPermitClient() == null) {
Swal.fire('Something went wrong!')
return
} else {
domainData = {
name: 'Dai Stablecoin',
version: '1',
chainId: 42,
verifyingContract: DAI_kovan_contract.address // kovan
}
tokenPermitOptions1 = {
spender: BICONOMY_CONTRACT,
domainData: domainData,
value: '100000000000000000000',
deadline: Math.floor(Date.now() / 1000 + 3600)
}
permitTx = await getPermitClient().daiPermit(tokenPermitOptions1)
// console.log('permitTx: ', permitTx, amountToApprove.currency.symbol, token.address, spender)
// addTransaction(permitTx, {
// summary: 'Approve ' + amountToApprove.currency.symbol,
// approval: { tokenAddress: token.address, spender: spender }
// })
await permitTx.wait(1)
console.log('permitTx: ', permitTx)
if (permitTx.hash) {
addTransaction(permitTx, {
summary: 'Approve ' + amountToApprove.currency.symbol,
approval: { tokenAddress: token.address, spender: spender }
})
}
return permitTx
}
} else if (tokenContract.address == USDC_kovan_contract.address) {
if (getPermitClient() == '' || getPermitClient() == 'undefined' || getPermitClient() == null) {
Swal.fire('Something went wrong!')
return
} else {
domainData = {
name: 'USDC Coin',
version: '1',
chainId: 42,
verifyingContract: USDC_kovan_contract.address
}
tokenPermitOptions1 = {
spender: BICONOMY_CONTRACT,
domainData: domainData,
value: '100000000000000000000',
deadline: Math.floor(Date.now() / 1000 + 3600)
}
permitTx = await getPermitClient().eip2612Permit(tokenPermitOptions1)
await permitTx.wait(1)
console.log('permitTx: ', permitTx)
if (permitTx.hash) {
addTransaction(permitTx, {
summary: 'Approve ' + amountToApprove.currency.symbol,
approval: { tokenAddress: token.address, spender: spender }
})
}
return permitTx
}
} else {
return tokenContract
.approve(spender, useExact ? amountToApprove.raw.toString() : MaxUint256, {
gasLimit: calculateGasMargin(estimatedGas)
})
.then((response: TransactionResponse) => {
console.log('permitTx', response)
addTransaction(response, {
summary: 'Approve ' + amountToApprove.currency.symbol,
approval: { tokenAddress: token.address, spender: spender }
})
})
.catch((error: Error) => {
console.debug('Failed to approve token', error)
throw error
})
}
} catch (error) {
console.log('Error: ', error)
}
}, [approvalState, token, tokenContract, amountToApprove, spender, addTransaction])
return [approvalState, approve]
}