Skip to content

Commit

Permalink
Merge branch 'main' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
efstajas committed Jul 31, 2024
2 parents b9027fd + 6477405 commit 4693dac
Show file tree
Hide file tree
Showing 14 changed files with 74 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@
{:else if error === 'too-large'}
File exceeds 5MB
{:else if error === 'upload-failed'}
Upload failed. Pleae try again later.
Upload failed. Please try again later.
{:else if error === 'too-many-files'}
Only drop a single file
{/if}
Expand Down
4 changes: 3 additions & 1 deletion src/lib/components/drip-list-badge/drip-list-badge.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,10 @@
export let disabled = false;
export let outline = false;
const ensConnected = ensStore.connected;
// lookup ens name if owner is provided
$: showOwner && dripList && ensStore.lookup(dripList.owner.address);
$: showOwner && dripList && $ensConnected && ensStore.lookup(dripList.owner.address);
$: ens = showOwner && dripList ? $ensStore[dripList.owner.address] : {};
$: username =
ens?.name ?? (dripList && showOwner && formatAddress(dripList.owner.address)) ?? undefined;
Expand Down
4 changes: 3 additions & 1 deletion src/lib/components/identity-badge/identity-badge.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@
export let isReverse = false;
export let tag: string | undefined = undefined;
$: ensStore.lookup(address);
const ensConnected = ensStore.connected;
$: $ensConnected && ensStore.lookup(address);
$: ens = $ensStore[address];
$: blockyUrl = `/api/blockies/${address}`;
Expand Down
4 changes: 2 additions & 2 deletions src/lib/components/search-bar/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import tokens from '$lib/stores/tokens';
import type { TokenInfoWrapper } from '$lib/stores/tokens/tokens.store';
import { get } from 'svelte/store';
import { isAddress } from 'ethers/lib/utils';
import { isSupportedGitUrl } from '$lib/utils/is-valid-git-url';
import { isValidGitUrl } from '$lib/utils/is-valid-git-url';
import GitProjectService from '$lib/utils/project/GitProjectService';

export enum SearchItemType {
Expand Down Expand Up @@ -74,7 +74,7 @@ export function updateSearchItems(accountId: string | undefined) {
export default function search(input: string | undefined) {
if (!input) return [];

if (isSupportedGitUrl(input)) {
if (isValidGitUrl(input)) {
const { username, repoName } = GitProjectService.deconstructUrl(input);

searchItems.push({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
import UnclaimedProjectCard, {
UNCLAIMED_PROJECT_CARD_FRAGMENT,
} from '$lib/components/unclaimed-project-card/unclaimed-project-card.svelte';
import { isSupportedGitUrl } from '$lib/utils/is-valid-git-url';
import { isSupportedGitUrl, isValidGitUrl } from '$lib/utils/is-valid-git-url';
import seededRandomElement from '$lib/utils/seeded-random-element';
import { page } from '$app/stores';
import possibleRandomEmoji from '$lib/utils/project/possible-random-emoji';
Expand Down Expand Up @@ -155,7 +155,7 @@
function submitInput() {
if (isSupportedGitUrl($context.gitUrl)) {
fetchProject();
} else {
} else if (isValidGitUrl($context.gitUrl) && !isSupportedGitUrl($context.gitUrl)) {
validationState = { type: 'invalid', message: 'Unsupported URL' };
}
}
Expand Down
28 changes: 23 additions & 5 deletions src/lib/stores/ens/ens.store.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { BaseProvider } from '@ethersproject/providers';
import type { ethers } from 'ethers';
import { get, writable } from 'svelte/store';
import walletStore from '../wallet/wallet.store';
import assert from '$lib/utils/assert';

export interface ResolvedRecord {
name?: string;
Expand All @@ -12,23 +14,34 @@ type State = {

export default (() => {
const state = writable<State>({});
const connected = writable(false);

let provider: ethers.providers.BaseProvider | undefined;

/**
* Connect the store to a provider, which is needed in order to resolve ENS
* records.
* @param toProvider The provider to connect to.
*/
function connect(toProvider: BaseProvider) {
provider = toProvider;
connected.set(true);
}

/**
* Perform an ENS lookup for the provided address, and append the result to the
* store state. Looks up ENS name & avatar URL.
* @param address The address to attempt resolving.
*/
async function lookup(address: string): Promise<ResolvedRecord | undefined> {
const { provider } = get(walletStore);

const saved = get(state)[address];
if (saved) return;

// Initially write an empty object to prevent multiple in-flight requests
// for the same name
state.update((s) => ({ ...s, [address]: {} }));

const lookups = [provider.lookupAddress(address), provider.getAvatar(address)];
const lookups = [provider?.lookupAddress(address), provider?.getAvatar(address)];

const [name, avatarUrl] = await Promise.all(lookups);

Expand Down Expand Up @@ -56,7 +69,10 @@ export default (() => {
* name in the store state.
*/
async function reverseLookup(name: string): Promise<string | undefined> {
const { provider } = get(walletStore);
assert(
provider,
'You need to `connect` the store to a provider before being able to reverse lookup',
);

const saved = Object.entries(get(state)).find((entry) => entry[1].name === name);

Expand All @@ -75,6 +91,8 @@ export default (() => {

return {
subscribe: state.subscribe,
connect,
connected: { subscribe: connected.subscribe },
lookup,
reverseLookup,
clear,
Expand Down
21 changes: 7 additions & 14 deletions src/lib/stores/ens/ens.store.unit.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { MockProvider } from '@rsksmart/mock-web3-provider';
import { get, readable } from 'svelte/store';
import { get } from 'svelte/store';
import ens from '.';
import walletStore from '../wallet/wallet.store';

vi.mock('@rsksmart/mock-web3-provider', () => ({
MockProvider: vi.fn().mockImplementation(() => ({
Expand All @@ -10,18 +9,16 @@ vi.mock('@rsksmart/mock-web3-provider', () => ({
})),
}));

vi.mock('$lib/stores/wallet/wallet.store', () => ({
default: readable({
provider: new MockProvider(),
}),
}));
const provider = new MockProvider();

afterEach(() => {
ens.clear();
});

describe('ens store', () => {
it('resolves records', async () => {
ens.connect(provider);

await ens.lookup('0x1234');

const expectedResult = {
Expand All @@ -33,18 +30,14 @@ describe('ens store', () => {
});

it('deduplicates requests', async () => {
const mockProvider = get(walletStore).provider;
const lookupSpy = vi.spyOn(mockProvider, 'lookupAddress');
const getAvatarSpy = vi.spyOn(mockProvider, 'getAvatar');
ens.connect(provider);

ens.lookup('0x1234');
ens.lookup('0x1234');
ens.lookup('0x1234');
ens.lookup('0x1234');
ens.lookup('0x1235');
ens.lookup('0x1235');

expect(lookupSpy).toHaveBeenCalledTimes(2);
expect(getAvatarSpy).toHaveBeenCalledTimes(2);
expect(provider.lookupAddress).toHaveBeenCalledTimes(2);
expect(provider.getAvatar).toHaveBeenCalledTimes(2);
});
});
4 changes: 2 additions & 2 deletions src/lib/utils/build-repo-url.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BASE_URL } from './base-url';
import { isSupportedGitUrl } from './is-valid-git-url';
import { isValidGitUrl } from './is-valid-git-url';

export function isDripsProjectUrl(value: string): boolean {
return value.includes(`${BASE_URL}/app/projects/`);
Expand All @@ -24,7 +24,7 @@ export function buildRepositoryURL(url: string): string {
if (forge === 'github') {
const githubUrl = `https://github.com/${repoPath}`;

if (isSupportedGitUrl(githubUrl)) {
if (isValidGitUrl(githubUrl)) {
return `https://github.com/${repoPath}`;
}

Expand Down
16 changes: 16 additions & 0 deletions src/lib/utils/decode-universal-account-id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import ens from '$lib/stores/ens';
import { getAddressDriverClient } from '$lib/utils/get-drips-clients';
import { isAddress } from 'ethers/lib/utils';
import { AddressDriverClient, Utils } from 'radicle-drips';
import { get } from 'svelte/store';

interface AddressDriverResult {
driver: 'address';
Expand Down Expand Up @@ -40,6 +41,21 @@ export default async function (
dripsAccountId,
};
} else if (universalAcccountIdentifier.endsWith('.eth')) {
// Subscribe to ens.connected store and wait until it's true

const ensConnected = ens.connected;

if (!get(ensConnected)) {
await new Promise((resolve) => {
const unsubscribe = ensConnected.subscribe((connected) => {
if (connected) {
unsubscribe();
resolve(undefined);
}
});
});
}

const lookup = await ens.reverseLookup(universalAcccountIdentifier);
if (lookup) {
const dripsAccountId = await (await getAddressDriverClient()).getAccountIdByAddress(lookup);
Expand Down
10 changes: 4 additions & 6 deletions src/lib/utils/is-valid-git-url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,10 @@ function validateUrl(url: string, allowedHosts: string[]): boolean {
}
}

export function isSupportedGitUrl(url: string): boolean {
const githubUrlRegex = /^https:\/\/github\.com\/[\w-]+\/[\w.-]+$/;

if (!githubUrlRegex.test(url)) {
return false;
}
export function isValidGitUrl(url: string): boolean {
return validateUrl(url, ['github.com', 'gitlab.com']);
}

export function isSupportedGitUrl(url: string): boolean {
return validateUrl(url, ['github.com']);
}
2 changes: 1 addition & 1 deletion src/routes/api/custom-avatars/upload/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const POST = async ({ request }) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(stream as any)['path'] = 'avatar.png';

const pin = await pinata.pinFileToIPFS(stream);
const pin = await pinata.pinFileToIPFS(stream, { pinataMetadata: { name: 'avatar' } });

return new Response(JSON.stringify(pin));
};
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import checkIsUser from '$lib/utils/check-is-user';
import decodeAccountId from '$lib/utils/decode-universal-account-id';
import LargeEmptyState from '$lib/components/large-empty-state/large-empty-state.svelte';
// import collectFlowSteps from '$lib/flows/collect-flow/collect-flow-steps';
import getWithdrawSteps from '$lib/flows/withdraw-flow/withdraw-flow-steps';
import topUpFlowSteps from '$lib/flows/top-up-flow/top-up-flow-steps';
import addCustomTokenFlowSteps from '$lib/flows/add-custom-token/add-custom-token-flow-steps';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import { getRepoDriverClient } from '$lib/utils/get-drips-clients';
import { Forge } from 'radicle-drips';
import cached from '$lib/utils/cache/remote/cached';
import queryCacheKey from '$lib/utils/cache/remote/query-cache-key';
import { isSupportedGitUrl } from '$lib/utils/is-valid-git-url';

async function fetchDripsProject(repoUrl: string) {
const getProjectsQuery = gql`
Expand All @@ -33,15 +32,18 @@ async function fetchDripsProject(repoUrl: string) {

const cacheKey = queryCacheKey(getProjectsQuery, [repoUrl], `project-page:${accountId}`);

return await cached(redis, cacheKey, 172800, () =>
query<ProjectByUrlQuery, ProjectByUrlQueryVariables>(
return await cached(
redis,
cacheKey,
172800,
() => query<ProjectByUrlQuery, ProjectByUrlQueryVariables>(
getProjectsQuery,
{
url: repoUrl,
},
fetch,
),
);
)
}

export const load = (async ({ params, fetch, url }) => {
Expand All @@ -66,8 +68,6 @@ export const load = (async ({ params, fetch, url }) => {

const repoUrl = `https://github.com/${githubUsername}/${githubRepoName}`;

if (!isSupportedGitUrl(repoUrl)) throw error(404);

const [repoRes, projectRes] = await Promise.all([
fetch(`/api/github/${encodeURIComponent(repoUrl)}`),
fetchDripsProject(repoUrl),
Expand Down
4 changes: 3 additions & 1 deletion src/routes/app/+layout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@
await wallet.initialize();
loaded = true;
const { connected, network, address, safe } = $wallet;
const { connected, network, provider, address, safe } = $wallet;
ens.connect(provider);
themeStore.subscribe((v) => {
const onboardTheme = v.currentTheme === 'h4x0r' ? 'dark' : v.currentTheme;
Expand Down

0 comments on commit 4693dac

Please sign in to comment.