Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ NEXT_PUBLIC_ENABLE_STAKING=true
# Force-build the /dev/components showcase. Automatic on `next dev` and Vercel previews.
NEXT_PUBLIC_ENABLE_DEV_PAGES=false
NEXT_PUBLIC_API_BASEURL=https://aave-api-v2.aave.com
# Aave SDK backend: production | staging | local (optional, defaults to production)
NEXT_PUBLIC_BACKEND_ENVIRONMENT=
# Overrides the GraphQL URL of the backend environment above, keeping its other settings (optional)
NEXT_PUBLIC_GRAPHQL_ENDPOINT=
NEXT_PUBLIC_TRANSAK_APP_URL=https://global.transak.com
NEXT_PUBLIC_TRANSAK_API_URL=https://api.transak.com
NEXT_PUBLIC_TRANSAK_API_KEY=799087ea-c2be-44b8-a0fe-56d96b37ee3c
Expand Down
3 changes: 2 additions & 1 deletion pages/_app.page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { Web3ContextProvider } from 'src/libs/web3-data-provider/Web3Provider';
import { useRootStore } from 'src/store/root';
import { SharedDependenciesProvider } from 'src/ui-config/SharedDependenciesProvider';
import { wagmiConfig } from 'src/ui-config/wagmiConfig';
import { SDK_ENVIRONMENT } from 'src/utils/sdkEnvironment';
import { WagmiProvider } from 'wagmi';

import createEmotionCache from '../src/createEmotionCache';
Expand Down Expand Up @@ -116,7 +117,7 @@ type NextPageWithLayout = NextPage & {
getLayout?: (page: React.ReactElement) => React.ReactNode;
};

export const client = AaveClient.create();
export const client = AaveClient.create({ environment: SDK_ENVIRONMENT });

interface MyAppProps extends AppProps {
emotionCache?: EmotionCache;
Expand Down
39 changes: 4 additions & 35 deletions src/hooks/app-data-provider/useMarketsData.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,9 @@
import { AaveClient, chainId, evmAddress, OrderDirection } from '@aave/client';
import { MarketsQuery } from '@aave/graphql';
import { markets } from '@aave/client/actions';
import { useQuery } from '@tanstack/react-query';
import { FieldNode, Kind, visit } from 'graphql';
import { MarketDataType } from 'src/ui-config/marketsConfig';
import { queryKeysFactory } from 'src/ui-config/queries';

// TEMPORARY WORKAROUND: remove once the backend resolves Merkl payout tokens on
// their own chain.
//
// A Merkl campaign can pay out on a different chain than its market (e.g. an
// X Layer campaign paying mainnet USDC). The API currently labels the payout
// token with the market's chain, so resolving its `decimals`/`name`/`symbol`
// calls a non-existent contract and fails the whole `markets` query, which
// blanks the market page. The interface never reads `payoutToken`, so we send
// the SDK's own Markets document with `payoutToken` trimmed to fields that need
// no on-chain lookup. Same shape as the SDK's `markets()` action otherwise.
const SAFE_PAYOUT_TOKEN_FIELDS = ['__typename', 'address', 'chainId'];

const SafeMarketsQuery = visit(MarketsQuery, {
Field(node): FieldNode | undefined {
if (node.name.value !== 'payoutToken') return undefined;
return {
...node,
selectionSet: {
kind: Kind.SELECTION_SET,
selections: SAFE_PAYOUT_TOKEN_FIELDS.map((field) => ({
kind: Kind.FIELD,
name: { kind: Kind.NAME, value: field },
})),
},
};
},
}) as typeof MarketsQuery;

type UseMarketsDataParams = {
client: AaveClient;
marketData: MarketDataType;
Expand All @@ -50,11 +21,9 @@ export const useMarketsData = ({ client, marketData, account }: UseMarketsDataPa
queryKey: marketKey,
enabled: !!client,
queryFn: async () => {
const response = await client.query(SafeMarketsQuery, {
request: {
chainIds: [chainId(marketData.chainId)],
user: userAddress,
},
const response = await markets(client, {
chainIds: [chainId(marketData.chainId)],
user: userAddress,
suppliesOrderBy: { tokenName: OrderDirection.Asc },
borrowsOrderBy: { tokenName: OrderDirection.Asc },
});
Expand Down
87 changes: 87 additions & 0 deletions src/utils/queryHash.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// The edge cache keys GraphQL responses on the sha256 of the POST body, one comma-separated hash per element for a batch
const QUERY_HASH_HEADER = 'x-query-hash';

const installed = Symbol.for('aave-interface.queryHashFetch');

async function sha256Hex(body: string): Promise<string> {
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(body));
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');
}

// Sliced from the text rather than re-serialised, so the bytes match what the edge hashes
function splitElements(text: string): string[] | null {
try {
if (!Array.isArray(JSON.parse(text))) return null;
} catch {
return null;
}

const elements: string[] = [];
let start = text.indexOf('[') + 1;
let depth = 0;
let inString = false;
let escaped = false;

for (let i = start; i < text.length; i++) {
const c = text[i];

if (inString) {
if (escaped) escaped = false;
else if (c === '\\') escaped = true;
else if (c === '"') inString = false;
} else if (c === '"') {
inString = true;
} else if (c === '{' || c === '[') {
depth++;
} else if ((c === '}' || c === ']') && depth > 0) {
depth--;
} else if ((c === ',' || c === ']') && depth === 0) {
const element = text.slice(start, i).trim();
if (element.length > 0) elements.push(element);
if (c === ']') break;
start = i + 1;
}
}

return elements;
}

async function queryHash(body: string): Promise<string> {
const elements = body.trimStart().startsWith('[') ? splitElements(body) : null;
if (elements === null || elements.length === 0) return sha256Hex(body);

return (await Promise.all(elements.map(sha256Hex))).join(',');
}

function requestUrl(input: RequestInfo | URL): string | null {
if (typeof input === 'string') return input;
if (input instanceof URL) return input.href;
return null;
}

// The SDK exposes neither a custom fetch nor per-request headers, so the global fetch is wrapped instead
export function installQueryHashFetch(endpoint: string) {
if (typeof globalThis.fetch !== 'function') return;
if (typeof crypto === 'undefined' || !crypto.subtle) return;

const current = globalThis.fetch as typeof fetch & { [installed]?: true };
if (current[installed]) return;

const original = current;
const wrapped: typeof fetch = async (input, init) => {
const url = requestUrl(input);
if (
!url?.startsWith(endpoint) ||
init?.method?.toUpperCase() !== 'POST' ||
typeof init.body !== 'string'
) {
return original(input, init);
}

const headers = new Headers(init.headers);
headers.set(QUERY_HASH_HEADER, await queryHash(init.body));
return original(input, { ...init, headers });
};

globalThis.fetch = Object.assign(wrapped, { [installed]: true as const });
}
21 changes: 21 additions & 0 deletions src/utils/sdkEnvironment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { local, production, staging } from '@aave/react';

import { installQueryHashFetch } from './queryHash';

const SDK_ENVIRONMENT_PRESET = (() => {
switch (process.env.NEXT_PUBLIC_BACKEND_ENVIRONMENT) {
case 'local':
return local;
case 'staging':
return staging;
default:
return production;
}
})();

export const SDK_ENVIRONMENT = {
...SDK_ENVIRONMENT_PRESET,
backend: process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT || SDK_ENVIRONMENT_PRESET.backend,
};

installQueryHashFetch(SDK_ENVIRONMENT.backend);
Loading