Skip to content

Commit

Permalink
claim and bridge working
Browse files Browse the repository at this point in the history
  • Loading branch information
brunobar79 committed Jun 23, 2024
1 parent 8d40d1d commit ec9d7fa
Show file tree
Hide file tree
Showing 6 changed files with 127 additions and 77 deletions.
2 changes: 1 addition & 1 deletion src/graphql/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ exports.config = {
document: './queries/ens.graphql',
schema: {
method: 'POST',
url: 'https://api.thegraph.com/subgraphs/name/ensdomains/ens',
url: 'https://gateway-arbitrum.network.thegraph.com/api/35a75cae48aab2b771d1e53543a37a0f/subgraphs/id/5XqPmWe6gjyrJtFn9cLy237i4cWw2j9HcUJEXsP5qGtH',
},
},
metadata: {
Expand Down
22 changes: 4 additions & 18 deletions src/raps/actions/claim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ const CLAIM_MOCK_DATA = {
},
};

const DO_FAKE_CLAIM = false;

// This action is used to claim the rewards of the user
// by making an api call to the backend which would use a relayer
// to do the claim and send the funds to the user
Expand All @@ -18,50 +20,34 @@ export async function claim({ parameters, wallet, baseNonce }: ActionProps<'clai
if (!address) {
throw new Error('Invalid address');
}

console.log('claim action called with params', parameters);
// when IS_TESTING is true, we use mock data (can do as many as we want)
// when DO_FAKE_CLAIM is true, we use mock data (can do as many as we want)
// otherwise we do a real claim (can be done once, then backend needs to reset it)
const claimInfo = process.env.IS_TESTING === 'true' ? CLAIM_MOCK_DATA : await metadataPOSTClient.claimUserRewards({ address });

// Just for testing purposes so we know what the state of the ENV VARS are
console.log('ENV VARS', {
IS_TESTING: process.env.IS_TESTING,
INTERNAL_BUILD: process.env.INTERNAL_BUILD,
});
const claimInfo = DO_FAKE_CLAIM ? CLAIM_MOCK_DATA : await metadataPOSTClient.claimUserRewards({ address });

console.log('got claim tx hash', claimInfo);
// Checking ig we got the tx hash
const txHash = claimInfo.claimUserRewards?.txHash;
if (!txHash) {
// If there's no transaction hash the relayer didn't submit the transaction
// so we can't contnue
console.log('did not get tx hash', claimInfo);
throw new Error('Failed to claim rewards');
}

console.log('getting claim tx');
// We need to make sure the transaction is mined
// so we get the transaction
const claimTx = await wallet?.provider?.getTransaction(txHash);
console.log('got claim tx', claimTx);
console.log('waiting for claim tx to be mined');

// then we wait for the receipt of the transaction
// to conirm it was mined
const receipt = await claimTx?.wait();
console.log('got claim tx receipt', receipt);

// finally we check if the transaction was successful
const success = receipt?.status === 1;
if (!success) {
// The transaction failed, we can't continue
console.log('claim tx failed', receipt);
throw new Error('Failed to claim rewards');
}

// If the transaction was successful we can return the hash
console.log('Claimed succesful');

return {
nonce: (baseNonce || 0) - 1,
Expand Down
41 changes: 5 additions & 36 deletions src/raps/actions/claimBridge.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,27 @@
import { AddressZero } from '@ethersproject/constants';
import { ChainId, CrosschainQuote, QuoteError, SwapType, getClaimBridgeQuote } from '@rainbow-me/swaps';
import BigNumber from 'bignumber.js';
import { CrosschainQuote, QuoteError, SwapType, getClaimBridgeQuote } from '@rainbow-me/swaps';
import { Address } from 'viem';
import { ActionProps } from '../references';
import { executeCrosschainSwap } from './crosschainSwap';
import { RainbowError, logger } from '@/logger';
import { TransactionGasParams } from '@/__swaps__/types/gas';
import { add, lessThan, multiply, subtract } from '@/helpers/utilities';
import { getProviderForNetwork } from '@/handlers/web3';
import { Network } from '@/helpers';
import { TxHash } from '@/resources/transactions/types';
import { NewTransaction } from '@/entities';
import { NewTransaction, TransactionGasParamAmounts } from '@/entities';
import { addNewTransaction } from '@/state/pendingTransactions';
import { getNetworkFromChainId } from '@/utils/ethereumUtils';
import { getSelectedGas } from '@/__swaps__/screens/Swap/hooks/useSelectedGas';

// This action is used to bridge the claimed funds to another chain
export async function claimBridge({ parameters, wallet, baseNonce }: ActionProps<'claimBridge'>) {
const { address, toChainId, sellAmount, chainId } = parameters;
console.log('claimBridge action called with params', parameters);

// Check if the address and toChainId are valid
// otherwise we can't continue
if (!toChainId || !address) {
throw new RainbowError('claimBridge: error getClaimBridgeQuote');
}

console.log('getting claim bridge quote');

let maxBridgeableAmount = sellAmount;
let needsNewQuote = false;

Expand All @@ -43,8 +37,6 @@ export async function claimBridge({ parameters, wallet, baseNonce }: ActionProps
swapType: SwapType.crossChain,
});

console.log('got claim bridge quote', claimBridgeQuote);

// if we don't get a quote or there's an error we can't continue
if (!claimBridgeQuote || (claimBridgeQuote as QuoteError)?.error) {
throw new RainbowError('claimBridge: error getClaimBridgeQuote');
Expand All @@ -55,42 +47,30 @@ export async function claimBridge({ parameters, wallet, baseNonce }: ActionProps
// 2 - We use the default gas limit (already inflated) from the quote to calculate the aproximate gas fee
const initalGasLimit = bridgeQuote.defaultGasLimit as string;

const selectedGas = getSelectedGas(parameters.chainId);
console.log('selectedGas', selectedGas);
// Force typing since we only deal with 1559 gas params here
const gasParams = selectedGas as unknown as TransactionGasParams;
const gasParams = parameters.gasParams as TransactionGasParamAmounts;
const feeAmount = add(gasParams.maxFeePerGas, gasParams.maxPriorityFeePerGas);
console.log('fee amount', new BigNumber(feeAmount).toNumber());
const gasFeeInWei = multiply(initalGasLimit, feeAmount);
console.log('gas fee in wei', new BigNumber(gasFeeInWei).toNumber());

// 3 - Check if the user has enough balance to pay the gas fee
const provider = getProviderForNetwork(Network.optimism);

const balance = await provider.getBalance(address);
console.log('balance', balance.toString());

// if the balance minus the sell amount is less than the gas fee we need to make adjustments
if (lessThan(subtract(balance.toString(), sellAmount), gasFeeInWei)) {
// if the balance is less than the gas fee we can't continue
if (lessThan(sellAmount, gasFeeInWei)) {
console.log('not enough balance to bridge at all');
throw new RainbowError('claimBridge: error insufficient funds to pay gas fee');
} else {
// otherwie we bridge the maximum amount we can afford
console.log('enough balance to bridge some');
maxBridgeableAmount = subtract(sellAmount, gasFeeInWei);
console.log('will bridge instead', {
claimed: sellAmount,
maxBridgeableAmount,
});
needsNewQuote = true;
}
}

// if we need to bridge a different amount we get a new quote
if (needsNewQuote) {
console.log('getting new quote with maxBridgeableAmount');
const newQuote = await getClaimBridgeQuote({
chainId,
toChainId,
Expand All @@ -102,10 +82,7 @@ export async function claimBridge({ parameters, wallet, baseNonce }: ActionProps
swapType: SwapType.crossChain,
});

console.log('got new quote', newQuote);

if (!newQuote || (newQuote as QuoteError)?.error) {
console.log('error getting new quote', newQuote);
throw new RainbowError('claimBridge: error getClaimBridgeQuote (new)');
}

Expand All @@ -115,7 +92,6 @@ export async function claimBridge({ parameters, wallet, baseNonce }: ActionProps
// now that we have a valid quote for the maxBridgeableAmount we can estimate the gas limit
let gasLimit;
try {
console.log('estimating gas limit');
try {
gasLimit = await provider.estimateGas({
from: address,
Expand All @@ -125,10 +101,9 @@ export async function claimBridge({ parameters, wallet, baseNonce }: ActionProps
...gasParams,
});
} catch (e) {
console.log('error estimating gas limit', e);
// Instead of failing we'll try using the default gas limit + 20%
gasLimit = (Number(bridgeQuote.defaultGasLimit) * 1.2).toString();
}

console.log('estimated gas limit', gasLimit);
} catch (e) {
logger.error(new RainbowError('crosschainSwap: error estimateCrosschainSwapGasLimit'), {
message: (e as Error)?.message,
Expand Down Expand Up @@ -156,11 +131,8 @@ export async function claimBridge({ parameters, wallet, baseNonce }: ActionProps

let swap;
try {
console.log('claimBridge executing crosschain swap', swapParams);
swap = await executeCrosschainSwap(swapParams);
console.log('claimBridge executed crosschain swap', swap);
} catch (e) {
console.log('claimBridge executeCrosschainSwap error', e);
logger.error(new RainbowError('crosschainSwap: error executeCrosschainSwap'), { message: (e as Error)?.message });
throw e;
}
Expand Down Expand Up @@ -209,15 +181,12 @@ export async function claimBridge({ parameters, wallet, baseNonce }: ActionProps
...gasParams,
} satisfies NewTransaction;

console.log('claimBridge adding new transaction', transaction);

addNewTransaction({
address: bridgeQuote.from as Address,
network: getNetworkFromChainId(parameters.chainId),
transaction,
});

console.log('claimBridge returning nonce and hash', swap.nonce, swap.hash);
return {
nonce: swap.nonce,
hash: swap.hash,
Expand Down
3 changes: 2 additions & 1 deletion src/raps/claimAndBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { RapAction, RapClaimActionParameters } from './references';

export const createClaimAndBridgeRap = async (claimParameters: RapClaimActionParameters) => {
let actions: RapAction<'crosschainSwap' | 'claim' | 'claimBridge'>[] = [];
const { assetToSell, sellAmount, assetToBuy, meta, chainId, toChainId, address } = claimParameters;
const { assetToSell, sellAmount, assetToBuy, meta, chainId, toChainId, address, gasParams } = claimParameters;

const claim = createNewAction('claim', claimParameters);
actions = actions.concat(claim);
Expand All @@ -20,6 +20,7 @@ export const createClaimAndBridgeRap = async (claimParameters: RapClaimActionPar
sellAmount,
assetToBuy,
quote: undefined,
gasParams,
} satisfies RapClaimActionParameters);

actions = actions.concat(bridge);
Expand Down
1 change: 1 addition & 0 deletions src/raps/references.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ export interface RapClaimActionParameters {
chainId: ChainId;
toChainId?: ChainId;
quote: undefined;
gasParams: TransactionGasParamAmounts | LegacyTransactionGasParamAmounts;
}

export type RapActionParameters =
Expand Down
Loading

0 comments on commit ec9d7fa

Please sign in to comment.