Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug fixes discovered during testing. #40

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
2 changes: 1 addition & 1 deletion packages/snap/snap.manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/celo-org/gas-snap.git"
},
"source": {
"shasum": "Aglj//sQdE+aaLIrYZNEA9WcyK0iWd3JH+JGANbCXRQ=",
"shasum": "4QjBeigCYVIjhJXBCYDqJCEA+Rcos8XVuDjvnvXO+XA=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
4 changes: 4 additions & 0 deletions packages/snap/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,7 @@
export const REGISTRY_ADDRESS = '0x000000000000000000000000000000000000ce10';
export const CELO_MAINNET = 'mainnet';
export const CELO_ALFAJORES = 'alfajores';
export const REJECTION_MESSAGE = 'User rejected the request';
export const INVALID_CURRENCY_MESSAGE = 'Invalid Currency';
export const INSUFFICIENT_FUNDS_MESSAGE = `Insufficient funds for the provided gas currency to complete the operation. Please try again using another currency.`;
export const VALID_CURRENCIES = ['cusd', 'ceur', 'creal', 'celo'];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NIT: It's usually been convention to write these currencies in uppercase.

4 changes: 2 additions & 2 deletions packages/snap/src/currency.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,8 @@ export async function getOptimalFeeCurrency(
const gasLimit = (await wallet.estimateGas(tx)).mul(5);
const celoBalance = await wallet.getBalance();
const tokenAddresses = await feeCurrencyWhitelistContract.getWhitelist();

if (gasLimit.add(tx.value ?? 0) >= celoBalance) {
const gasLimitPlusValue = gasLimit.add(tx.value ?? 0);
if (gasLimitPlusValue.gt(celoBalance)) {
montera82 marked this conversation as resolved.
Show resolved Hide resolved
console.log('using stable token for gas');
const tokens: Contract[] = tokenAddresses.map(
(tokenAddress: string) =>
Expand Down
98 changes: 54 additions & 44 deletions packages/snap/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { constants } from 'ethers';
import { getNetworkConfig } from './utils/network';
import { RequestParamsSchema } from './utils/types';
import { handleNumber, isInsufficientFundsError } from './utils/utils';
import { handleNumber } from './utils/utils';
import { sendTransaction } from './sendTransaction';
import { getKeyPair } from './getKeyPair';
import {
Expand All @@ -12,6 +12,12 @@
getOptimalFeeCurrency,
} from './currency';
import { invokeSnapDialog } from './utils/snapDialog';
import {
INSUFFICIENT_FUNDS_MESSAGE,
INVALID_CURRENCY_MESSAGE,
REJECTION_MESSAGE,
VALID_CURRENCIES,
} from './constants';

/**
* Handle incoming JSON-RPC requests, sent through `wallet_invokeSnap`.
Expand All @@ -32,38 +38,44 @@
}

const { tx } = request.params;
tx.value = handleNumber(tx.value); // todo find way to do this within io-ts transformation
tx.value = handleNumber(tx.value);
const network = await getNetworkConfig();
const provider = new CeloProvider(network.url);
const keyPair = await getKeyPair(snap, tx.from);
const wallet = new CeloWallet(keyPair.privateKey).connect(provider);
tx.from = tx.from ? tx.from : wallet.address;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure why this line was added.

If tx.from does not exist, than wallet cannot be generated, since keypair is using tx.from

If tx.from could in some cases be missing, should there be a check before line 44 that tx.from actually exist?

if (tx.value === constants.Zero) {
delete tx.value;
}

switch (request.method) {
case 'celo_sendTransaction': {
const result = await invokeSnapDialog({
type: 'confirmation',
contentArray: [
'Please approve the following transaction',
tx.to ? `to: ${tx.to}` : '',
tx.from ? `from: ${tx.from}` : '',
tx.nonce ? `nonce: ${tx.nonce}` : '',
tx.gasLimit ? `gasLimit: ${tx.gasLimit}` : '',
tx.gasPrice ? `gasPrice: ${tx.gasPrice}` : '',
tx.data ? `data: ${tx.data}` : '',
tx.value ? `value: ${BigInt(tx.value?.toString())} wei` : '',
tx.chainId ? `chainId: ${tx.chainId}` : '',
tx.feeCurrency ? `feeCurrency: ${tx.feeCurrency}` : '',
tx.gatewayFeeRecipient
? `gatewayFeeRecipient: ${tx.gatewayFeeRecipient}`
: '',
tx.gatewayFee ? `gatewayFee: ${tx.gatewayFee}` : '',
].filter(Boolean), // This will remove any empty strings
});
case 'celo_sendTransaction':
{
const result = await invokeSnapDialog({
type: 'confirmation',
contentArray: [
'Please approve the following transaction',
tx.to ? `to: ${tx.to}` : '',
tx.from ? `from: ${tx.from}` : '',
tx.nonce ? `nonce: ${tx.nonce}` : '',
tx.gasLimit ? `gasLimit: ${tx.gasLimit}` : '',
tx.gasPrice ? `gasPrice: ${tx.gasPrice}` : '',
tx.data ? `data: ${tx.data}` : '',
tx.value ? `value: ${BigInt(tx.value?.toString())} wei` : '',
tx.chainId ? `chainId: ${tx.chainId}` : '',
tx.feeCurrency ? `feeCurrency: ${tx.feeCurrency}` : '',
tx.gatewayFeeRecipient
? `gatewayFeeRecipient: ${tx.gatewayFeeRecipient}`
: '',
tx.gatewayFee ? `gatewayFee: ${tx.gatewayFee}` : '',
].filter(Boolean), // This will remove any empty strings
});

if (result === false) {
// user did not proceed approve the request in the tx summary screen
throw new Error(REJECTION_MESSAGE);
}

if (result === true) {
tx.feeCurrency ??= await getOptimalFeeCurrency(tx, wallet);
const suggestedFeeCurrency = getFeeCurrencyNameFromAddress(
tx.feeCurrency,
Expand All @@ -73,25 +85,25 @@
const overrideFeeCurrency = await invokeSnapDialog({
type: 'prompt',
contentArray: [
`The suggested gas currency for your tx is ${suggestedFeeCurrency}`,
`The suggested gas currency for your tx is [${suggestedFeeCurrency.toUpperCase()}]`,
montera82 marked this conversation as resolved.
Show resolved Hide resolved
`If you would like to use a different gas currency, please enter it below`,
`Otherwise, press submit`,
],
placeholder: `'cusd', 'ceur', 'creal', 'celo'`,
placeholder: `cusd, ceur, creal, celo`,
});
if (
// TODO find a cleaner way to do this, probably use an enum
overrideFeeCurrency === 'cusd' ||
overrideFeeCurrency === 'ceur' ||
overrideFeeCurrency === 'creal' ||
overrideFeeCurrency === 'celo'
) {

if (VALID_CURRENCIES.includes(overrideFeeCurrency.toLowerCase())) {
tx.feeCurrency = getFeeCurrencyAddressFromName(
overrideFeeCurrency,
overrideFeeCurrency.toLowerCase(),
network.name,
);
} else if (overrideFeeCurrency === null) {
return;
} else {
// user either rejected the request in the currency screen or entered an invalid currency
throw new Error(
overrideFeeCurrency === null
? REJECTION_MESSAGE
: INVALID_CURRENCY_MESSAGE,
);
}

try {
Expand All @@ -100,24 +112,22 @@
type: 'alert',
contentArray: [
'Your transaction succeeded!',
`${network.explorer}/tx/${txReceipt.transactionHash}`,
`${network.explorer}/tx/${txReceipt?.transactionHash}`,
],
});
} catch (error) {
let message = JSON.stringify(error);

if (isInsufficientFundsError(error)) {
message = `Oops! Looks like you don't have sufficient funds in the chosen gas currency to complete the operation. Please try again using another currency.`;
}

return txReceipt?.transactionHash;

Check failure on line 118 in packages/snap/src/index.ts

View workflow job for this annotation

GitHub Actions / Build, Lint, and Test (16.x)

Async arrow function expected no return value

Check failure on line 118 in packages/snap/src/index.ts

View workflow job for this annotation

GitHub Actions / Build, Lint, and Test (18.x)

Async arrow function expected no return value
} catch (e) {
const message = (e as Error).message.includes('insufficient funds')
? INSUFFICIENT_FUNDS_MESSAGE
: (e as Error).message;
await invokeSnapDialog({
type: 'alert',
contentArray: ['Your transaction failed!', `error: ${message}`],
});
throw new Error(message);
}
}
break;
}
default:
throw new Error('Method not found.');
}
Expand Down
Loading