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

Add networkStore and runtime support for networks #1835

Merged
merged 69 commits into from
Feb 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
69 commits
Select commit Hold shift + click to select a range
172e161
start work on combined networks store
walmat Jan 29, 2025
9d9176a
basic chain merge functionality, store initial state functionality, a…
walmat Jan 30, 2025
1e56210
finish setData and custom chain functions
walmat Jan 31, 2025
db47ed3
revert changes to references/chains and network utils
walmat Jan 31, 2025
3c9bf0e
revert changes to references/chains and network utils
walmat Jan 31, 2025
3d344c0
Merge branch 'master' into @matthew/networks-store
walmat Jan 31, 2025
e4dff77
Update package.json
walmat Jan 31, 2025
3071a39
refresh lock
walmat Jan 31, 2025
b79288b
strip store and start fresh
walmat Feb 3, 2025
398d38b
Integrate backend-driven custom networks
walmat Feb 4, 2025
da9e61b
split out icon urls into two different store accessors
walmat Feb 4, 2025
04b3b09
networkStore initialState unit tests and fixes a few bugs found along…
walmat Feb 4, 2025
aa408df
add additional tests to cover user-added custom networks
walmat Feb 4, 2025
3735682
remove need for favorites migrations and implement mergeChainData fun…
walmat Feb 4, 2025
421a8a4
more work on networkStore store methods
walmat Feb 5, 2025
e32d15d
update custom network query to add address
walmat Feb 5, 2025
01b3d3f
Apply suggestions from code review
walmat Feb 6, 2025
efd9ff9
add more tests
walmat Feb 6, 2025
c3e7ae2
add rest of store methods to match static
walmat Feb 6, 2025
61bb261
Merge branch 'master' into @matthew/networks-store
walmat Feb 7, 2025
6dc7f26
initial replacement of references/chains file
walmat Feb 7, 2025
361c850
consume badgeUrl from backend driven networks and remove local assets
walmat Feb 7, 2025
343d490
expose methods to get user-added chains and all chains
walmat Feb 8, 2025
43e98f9
transform network order to Array and enabled to a Set
walmat Feb 8, 2025
b2b0146
rename userOverrides to userPreferences
walmat Feb 8, 2025
1495742
rewrite methods to clarify exactly what piece of data is exposed
walmat Feb 8, 2025
c775a23
merge latest networks store changes
walmat Feb 8, 2025
0c281a5
remove rainbowChains and userChains references
walmat Feb 9, 2025
632a924
lots of initial state changes, and bug fixes
walmat Feb 10, 2025
a0385d8
Cleanup hardcoded network values and replace with backend driven (#1836)
walmat Feb 10, 2025
169ade9
Delete .vscode/settings.json
walmat Feb 10, 2025
ab58605
Merge branch 'master' into @matthew/networks-store
walmat Feb 10, 2025
f4fe45c
addCustomChain -> createParamaterizedSelector
walmat Feb 10, 2025
3d14b23
Merge branch '@matthew/runtime-support' of https://github.com/rainbow…
walmat Feb 10, 2025
3749ce0
merge latest master changes
walmat Feb 10, 2025
5d6da8a
add default favorites initial state
walmat Feb 10, 2025
81cbf8e
remove selectors from state mutation functions
walmat Feb 10, 2025
02f7b64
fix sync issue with createSelector and createParameterizedSelector
walmat Feb 11, 2025
58fd2d9
fix tests and cleanup
walmat Feb 11, 2025
984aed1
fix uniqueId
walmat Feb 11, 2025
735271f
bug fixes with dnd user chosen order and testnets being displayed
walmat Feb 12, 2025
8f51f0a
fix user assets
walmat Feb 12, 2025
fa4fcbe
use uncropped badge URL, swaps fixes, token search improvements
walmat Feb 12, 2025
2d46255
change main chains to be based off backend networks not all chains
walmat Feb 12, 2025
6a2d1e5
remove react-fast-compare
walmat Feb 12, 2025
dfd7129
tweak main chains logic more
walmat Feb 12, 2025
5c83fa7
fix some incoming provider checks and total wallet balance display
walmat Feb 12, 2025
98222ac
fix default slippage being stored in wrong key
walmat Feb 12, 2025
8f314af
fix send asset sorting
walmat Feb 13, 2025
55a0953
fix missing testnets in supported chains
walmat Feb 13, 2025
c53c8e5
fix mainChains functionality which broke send e2e
walmat Feb 13, 2025
e806503
fix invalid hook call
walmat Feb 13, 2025
0ccb171
fix case where we want to add custom rpcs to an existing chain
walmat Feb 13, 2025
548ca50
tweak custom chain additions
walmat Feb 13, 2025
96bad47
fix default favorites
walmat Feb 13, 2025
47d3e82
fix dapp interactions e2e
walmat Feb 14, 2025
97c3d25
fix edge case where new users wouldn't be have user preferences defined
walmat Feb 14, 2025
26ba053
disable broken swaps test
walmat Feb 14, 2025
4e5cbd8
fix swaps e2e failing on max base fee
walmat Feb 14, 2025
3a4e107
fixed testnets showing during non testnet mode
walmat Feb 14, 2025
683fa61
fix custom assets not working due to addys filtering
walmat Feb 14, 2025
d54c015
undo change to useUserChains that breaks filtering
walmat Feb 14, 2025
c2328aa
rm erraneous console logs
walmat Feb 19, 2025
06d4b36
Merge branch 'master' into @matthew/runtime-support
walmat Feb 19, 2025
916a768
Merge branch 'master' into @matthew/runtime-support
BrodyHughes Feb 19, 2025
0418b4c
Merge branch 'master' into @matthew/runtime-support
BrodyHughes Feb 19, 2025
324e4fe
change testnet endpoint
BrodyHughes Feb 19, 2025
0c1aa19
Merge branch 'master' into @matthew/runtime-support
BrodyHughes Feb 19, 2025
d5ea97f
Merge branch 'master' into @matthew/runtime-support
DanielSinclair Feb 19, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion e2e/serial/send/3_customNetworks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ it('should be able to add a custom testnet network', async () => {
await typeOnTextInput({ text: 'Telos EVM Testnet', driver });
await executePerformShortcut({ driver, key: 'TAB' });
await typeOnTextInput({
text: 'https://testnet.telos.net/evm',
text: 'https://rpc.testnet.telos.net',
driver,
});
await executePerformShortcut({ driver, key: 'TAB' });
Expand Down
2 changes: 1 addition & 1 deletion e2e/serial/swap/1_swapFlow1.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ it('should be able to open token to buy input and select assets', async () => {
expect(toBuyInputDaiSelected).toBeTruthy();
});

it('should be able to type native amount on sell input', async () => {
it.skip('should be able to type native amount on sell input', async () => {
Copy link
Member

Choose a reason for hiding this comment

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

Can you provide any info on this one? I can make a ticket but making sure this was intentional.

Copy link
Member

Choose a reason for hiding this comment

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

so for context: this failure has been happening since my PR was merged (#1830). I think something with the quotes changed and I need to fix it. I recommended skipping this for now so we have an actual working e2e in the meantime.

await findElementByTestIdAndClick({
id: 'token-to-sell-info-fiat-value-input',
driver,
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
"// Build and zip": "",
"bundle": "yarn build && yarn zip",
"// Runs tests": "",
"anvil": "anvil --fork-url $(./scripts/get-rpc-url.sh mainnet) --fork-block-number 21574102 --block-base-fee-per-gas 5000000000 --block-gas-limit 30000000",
"anvil": "anvil --fork-url $(./scripts/get-rpc-url.sh mainnet) --fork-block-number 21574102 --block-base-fee-per-gas 1000000000 --block-gas-limit 30000000",
Copy link
Member

Choose a reason for hiding this comment

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

Did this have a material effect on e2e?

Copy link
Member

Choose a reason for hiding this comment

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

Yes it did. Bruno actually recommended it a few weeks ago if we saw more of a specific failure type which matthew was seeing. Again, i recommended this and it did fix an issue.

"anvil:optimism": "anvil --fork-url $(./scripts/get-rpc-url.sh optimism)",
"anvil:kill": "lsof -i :8545|tail -n +2|awk '{print $2}'|xargs -r kill -s SIGINT",
"test": "./scripts/unit-tests.sh",
Expand Down Expand Up @@ -166,7 +166,7 @@
"viem": "2.21.55",
"wagmi": "2.8.1",
"word-wrap": "1.2.4",
"zustand": "4.1.5"
"zustand": "4.5.5"
},
"devDependencies": {
"@foundry-rs/hardhat-anvil": "0.1.7",
Expand Down
103 changes: 15 additions & 88 deletions scripts/networks.js
Original file line number Diff line number Diff line change
@@ -1,106 +1,28 @@
/* eslint-disable @typescript-eslint/no-var-requires */
const path = require('path');
const { BACKEND_NETWORKS_QUERY, CUSTOM_NETWORKS_QUERY } = require('../src/core/resources/networks/queries');

const fs = require('fs-extra');

/**
* Fetches data from the GraphQL API and saves it to a JSON file.
*/
async function fetchData() {
const graphqlQuery = `
query getNetworks($device: Device!, $includeTestnets: Boolean!) {
networks(device: $device, includeTestnets: $includeTestnets) {
id
name
label
icons {
badgeURL
}
testnet
internal
opStack
defaultExplorer {
url
label
transactionURL
tokenURL
}
defaultRPC {
enabledDevices
url
}
gasUnits {
basic {
approval
swap
swapPermit
eoaTransfer
tokenTransfer
}
wrapped {
wrap
unwrap
}
}
nativeAsset {
address
name
symbol
decimals
iconURL
colors {
primary
fallback
shadow
}
}
nativeWrappedAsset {
address
name
symbol
decimals
iconURL
colors {
primary
fallback
shadow
}
}
enabledServices {
meteorology {
enabled
}
swap {
enabled
}
addys {
approvals
transactions
assets
positions
}
tokenSearch {
enabled
}
nftProxy {
enabled
}
}
}
}
`;

async function fetchData(query) {
const response = await fetch('https://metadata.p.rainbow.me/v1/graph', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: graphqlQuery,
query,
variables: { device: 'BX', includeTestnets: true },
}),
});

const { data } = await response.json();
const filePath = path.join(__dirname, '../static/data/networks.json');
return data;
}

async function persistData(fileName, data) {
const filePath = path.join(__dirname, `../static/data/${fileName}.json`);

await fs.ensureFile(filePath);
await fs.writeJson(filePath, data);
Expand All @@ -109,7 +31,12 @@ async function fetchData() {
async function main() {
try {
console.log('Fetching networks ...');
await fetchData();
const [backendNetworks, customNetworks] = await Promise.all([
fetchData(BACKEND_NETWORKS_QUERY),
fetchData(CUSTOM_NETWORKS_QUERY),
]);
console.log('Persisting networks ...');
await persistData('networks', { backendNetworks, customNetworks });
console.log('Networks data fetched and available.');
process.exit(0);
} catch (error) {
Expand All @@ -118,4 +45,4 @@ async function main() {
}
}

main();
main();
60 changes: 23 additions & 37 deletions src/core/firebase/remoteConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import {

import { RainbowError, logger } from '~/logger';

import { ChainName } from '../types/chains';
import { networkStore } from '../state/networks/networks';
import { ChainId } from '../types/chains';

const firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY_BX,
Expand All @@ -30,25 +31,21 @@ export interface RainbowConfig extends Record<string, any> {
rewards_bridging_enabled: boolean;
degen_mode: boolean;
// SWAPS
default_slippage_bips: {
[ChainName.mainnet]: number;
[ChainName.optimism]: number;
[ChainName.polygon]: number;
[ChainName.arbitrum]: number;
[ChainName.base]: number;
[ChainName.zora]: number;
[ChainName.bsc]: number;
[ChainName.avalanche]: number;
[ChainName.blast]: number;
[ChainName.degen]: number;
[ChainName.apechain]: number;
[ChainName.ink]: number;
[ChainName.gravity]: number;
[ChainName.sanko]: number;
[ChainName.berachain]: number;
};
default_slippage_bips: Partial<Record<ChainId, number>>;
}

export const defaultslippagInBips = (chainId: ChainId) => {
switch (chainId) {
case ChainId.mainnet:
return 100;
case ChainId.bsc:
case ChainId.polygon:
return 200;
default:
return 500;
}
};

const DEFAULT_CONFIG = {
// features
send_enabled: true,
Expand All @@ -61,23 +58,12 @@ const DEFAULT_CONFIG = {
rewards_bridging_enabled: true,
degen_mode: false,
// SWAPS
default_slippage_bips: {
arbitrum: 500,
mainnet: 100,
optimism: 500,
polygon: 200,
base: 500,
zora: 500,
bsc: 200,
avalanche: 500,
blast: 500,
degen: 500,
apechain: 500,
ink: 500,
gravity: 500,
sanko: 500,
berachain: 500,
},
default_slippage_bips: Object.values(
networkStore.getState().getBackendSupportedChains(true),
).reduce<Partial<Record<ChainId, number>>>((acc, chain) => {
acc[chain.id] = defaultslippagInBips(chain.id);
return acc;
}, {}),
};

// Initialize with defaults in case firebase doesn't respond
Expand Down Expand Up @@ -114,8 +100,8 @@ export const init = async () => {
const realKey = key.replace('BX_', '');
// Ignore non BX keys
if (key.startsWith('BX_')) {
if (key === 'BX_default_slippage_bips') {
config[realKey] = JSON.parse(
if (key === 'BX_default_slippage_bips_chainId') {
config['default_slippage_bips'] = JSON.parse(
entry.asString(),
) as RainbowConfig['default_slippage_bips'];
} else if (
Expand Down
11 changes: 8 additions & 3 deletions src/core/providers/proxy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { ChainId } from '../types/chains';

const RPC_PROXY_BASE_URL = process.env.RPC_PROXY_BASE_URL;
const RPC_PROXY_API_KEY = process.env.RPC_PROXY_API_KEY;

const getHost = (endpoint: string) => {
try {
const host = new URL(endpoint).host;
Expand All @@ -25,9 +28,11 @@ export const proxyRpcEndpoint = (endpoint: string, chainId: ChainId) => {
!endpoint.match(/http:\/\/172.(1[6-9]|2[0-9]|3[0-1])./) &&
!isRainbowEndpoint(endpoint)
) {
return `${process.env.RPC_PROXY_BASE_URL}/${chainId}/${
process.env.RPC_PROXY_API_KEY
}?custom_rpc=${encodeURIComponent(endpoint)}`;
return `${RPC_PROXY_BASE_URL}/${chainId}/${RPC_PROXY_API_KEY}?custom_rpc=${encodeURIComponent(
endpoint,
)}`;
}

// NOTE: backend network endpoints are already proxied
return endpoint;
};
5 changes: 3 additions & 2 deletions src/core/raps/actions/crosschainSwap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
import { Address } from 'viem';

import { REFERRER, ReferrerType } from '~/core/references';
import { getChainGasUnits } from '~/core/references/chains';
import { networkStore } from '~/core/state/networks/networks';
import { ChainId } from '~/core/types/chains';
import { NewTransaction, TxHash } from '~/core/types/transactions';
import { isSameAssetInDiffChains } from '~/core/utils/assets';
Expand Down Expand Up @@ -45,7 +45,8 @@ export const estimateCrosschainSwapGasLimit = async ({
}): Promise<string> => {
const provider = getProvider({ chainId });
if (!provider || !quote) {
return getChainGasUnits(chainId).basic.swap;
const chainGasUnits = networkStore.getState().getChainGasUnits(chainId);
return chainGasUnits.basic.swap;
}
try {
if (requiresApprove) {
Expand Down
11 changes: 7 additions & 4 deletions src/core/raps/actions/swap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
import { Address } from 'viem';

import { metadataPostClient } from '~/core/graphql';
import { getChainGasUnits } from '~/core/references/chains';
import { networkStore } from '~/core/state/networks/networks';
import { ChainId } from '~/core/types/chains';
import { NewTransaction, TxHash } from '~/core/types/transactions';
import { add } from '~/core/utils/numbers';
Expand Down Expand Up @@ -60,17 +60,20 @@ export const estimateSwapGasLimit = async ({
const provider = getProvider({ chainId });

if (!provider || !quote) {
return getChainGasUnits(chainId).basic.swap;
const chainGasUnits = networkStore.getState().getChainGasUnits(chainId);
Copy link
Member

Choose a reason for hiding this comment

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

can pull this line out to line 61 and delete the duplicate line on 72

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Can, but only wanted to grab it when/if we needed to in order to reduce calls to the network store.

return chainGasUnits.basic.swap;
}

const isWrapNativeAsset = quote.swapType === SwapType.wrap;
const isUnwrapNativeAsset = quote.swapType === SwapType.unwrap;

// Wrap / Unwrap Eth
if (isWrapNativeAsset || isUnwrapNativeAsset) {
const chainGasUnits = networkStore.getState().getChainGasUnits(chainId);

const default_estimate = isWrapNativeAsset
? getChainGasUnits(chainId).wrapped.wrap
: getChainGasUnits(chainId).wrapped.unwrap;
? chainGasUnits.wrapped.wrap
: chainGasUnits.wrapped.unwrap;
try {
const gasLimit = await estimateGasWithPadding({
transactionRequest: {
Expand Down
Loading
Loading