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

Feat/token detail cache #7

Merged
merged 7 commits into from
Nov 8, 2023
Merged
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
112 changes: 112 additions & 0 deletions src/helper/soroban-rpc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import {
Networks,
Server,
TransactionBuilder,
BASE_FEE,
Contract,
TimeoutInfinite,
Transaction,
Memo,
MemoType,
Operation,
scValToNative,
} from "soroban-client";

type NetworkNames = keyof typeof Networks;

const SOROBAN_RPC_URLS: { [key in keyof typeof Networks]?: string } = {
TESTNET: "https://soroban-testnet.stellar.org/",
};

const getServer = async (network: NetworkNames) => {
const serverUrl = SOROBAN_RPC_URLS[network];
if (!serverUrl) {
throw new Error("network not supported");
}

return new Server(serverUrl, {
allowHttp: serverUrl.startsWith("http://"),
});
};

const getTxBuilder = async (
pubKey: string,
network: NetworkNames,
server: Server
) => {
const sourceAccount = await server.getAccount(pubKey);
return new TransactionBuilder(sourceAccount, {
fee: BASE_FEE,
networkPassphrase: Networks[network],
});
};

const simulateTx = async <ArgType>(
tx: Transaction<Memo<MemoType>, Operation[]>,
server: Server
): Promise<ArgType> => {
const simulatedTX = await server.simulateTransaction(tx);
if ("result" in simulatedTX && simulatedTX.result !== undefined) {
return scValToNative(simulatedTX.result.retval);
}

throw new Error("Invalid response from simulateTransaction");
};

const getTokenDecimals = async (
contractId: string,
server: Server,
builder: TransactionBuilder
) => {
const contract = new Contract(contractId);

const tx = builder
.addOperation(contract.call("decimals"))
.setTimeout(TimeoutInfinite)
.build();

const result = await simulateTx<number>(tx, server);
return result;
};

const getTokenName = async (
contractId: string,
server: Server,
builder: TransactionBuilder
) => {
const contract = new Contract(contractId);

const tx = builder
.addOperation(contract.call("name"))
.setTimeout(TimeoutInfinite)
.build();

const result = await simulateTx<string>(tx, server);
return result;
};

const getTokenSymbol = async (
contractId: string,
server: Server,
builder: TransactionBuilder
) => {
const contract = new Contract(contractId);

const tx = builder
.addOperation(contract.call("symbol"))
.setTimeout(TimeoutInfinite)
.build();

const result = await simulateTx<string>(tx, server);
return result;
};

export {
getServer,
getTokenDecimals,
getTokenName,
getTokenSymbol,
getTxBuilder,
simulateTx,
SOROBAN_RPC_URLS,
};
40 changes: 19 additions & 21 deletions src/helper/test-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,9 @@ const queryMockResponse = {
},
},
"query.getAccountBalances": {
edges: [
{
node: {
entryUpdateByContractIdAndKey: {
nodes: [
{
contractId:
"CCWAMYJME4H5CKG7OLXGC2T4M6FL52XCZ3OQOAV6LL3GLA4RO4WH3ASP",
keyXdr: tokenBalanceLedgerKey,
Expand All @@ -73,9 +73,7 @@ const queryMockResponse = {
ledger: "1",
entryDurability: "persistent",
},
},
{
node: {
{
contractId:
"CBGTG7XFRY3L6OKAUTR6KGDKUXUQBX3YDJ3QFDYTGVMOM7VV4O7NCODG",
keyXdr: tokenBalanceLedgerKey,
Expand All @@ -84,8 +82,8 @@ const queryMockResponse = {
ledger: "1",
entryDurability: "persistent",
},
},
],
],
},
},
[query.getAccountHistory]: {
eventByContractId: {
Expand Down Expand Up @@ -185,20 +183,20 @@ const mockMercuryClient = new MercuryClient(
renewClient,
testLogger
);

jest
.spyOn(mockMercuryClient, "tokenDetails")
.mockImplementation(
(..._args: Parameters<MercuryClient["tokenDetails"]>): any => {
return {
name: "Test Contract",
decimals: 7,
symbol: "TST",
};
}
);
async function getDevServer() {
const config = {
hostname: "localhost",
mode: "development",
mercuryEmail: "[email protected]",
mercuryKey: "xxx",
mercuryPassword: "pass",
mercuryBackend: "backend",
mercuryGraphQL: "graph-ql",
mercuryUserId: "user-id",
redisConnectionName: "freighter",
redisPort: 6379,
};
const server = initApiServer(mockMercuryClient, config);
const server = initApiServer(mockMercuryClient, testLogger);
await server.listen();
return server;
}
Expand Down
24 changes: 22 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as dotEnv from "dotenv";
import { expand } from "dotenv-expand";
import yargs from "yargs";
import { Client, fetchExchange } from "@urql/core";
import Redis from "ioredis";

import { logger } from "./logger";
import { buildConfig } from "./config";
Expand Down Expand Up @@ -57,14 +58,33 @@ async function main() {
password: conf.mercuryPassword,
userId: conf.mercuryUserId,
};

let redis = undefined;
// use in-memory store in dev
if (conf.mode !== "development") {
redis = new Redis({
connectionName: conf.redisConnectionName,
host: conf.hostname,
port: conf.redisPort,
connectTimeout: 500,
maxRetriesPerRequest: 1,
});

redis.on("error", (error) => {
logger.error(error);
throw new Error(JSON.stringify(error));
});
}

const mercuryClient = new MercuryClient(
conf.mercuryGraphQL,
mercurySession,
client,
renewClient,
logger
logger,
redis
);
const server = initApiServer(mercuryClient, conf);
const server = initApiServer(mercuryClient, logger, redis);

try {
await server.listen({ port });
Expand Down
22 changes: 14 additions & 8 deletions src/route/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,13 @@ describe("API routes", () => {
(server?.server?.address() as any).port
}/api/v1/account-balances/${pubKey}?contract_ids=CCWAMYJME4H5CKG7OLXGC2T4M6FL52XCZ3OQOAV6LL3GLA4RO4WH3ASP`
);
const { data } = await response.json();
const data = await response.json();
expect(response.status).toEqual(200);
expect(data.edges).toEqual(
queryMockResponse["query.getAccountBalances"].edges
);
for (const node of data) {
expect(node).toHaveProperty("contractId");
expect(node).toHaveProperty("keyXdr");
expect(node).toHaveProperty("valueXdr");
}
server.close();
});

Expand All @@ -60,11 +62,15 @@ describe("API routes", () => {
params as any
)}`
);
const { data } = await response.json();
const data = await response.json();
expect(response.status).toEqual(200);
expect(data.edges).toEqual(
queryMockResponse["query.getAccountBalances"].edges
);
expect(response.status).toEqual(200);
expect(data.length).toEqual(2);
for (const node of data) {
expect(node).toHaveProperty("contractId");
expect(node).toHaveProperty("keyXdr");
expect(node).toHaveProperty("valueXdr");
}
server.close();
});

Expand Down
30 changes: 13 additions & 17 deletions src/route/index.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,23 @@
import Fastify, { FastifyRequest } from "fastify";
import helmet from "@fastify/helmet";
import rateLimiter from "@fastify/rate-limit";
import Redis from "ioredis";
import { Logger } from "pino";
import { Redis } from "ioredis";

import { MercuryClient } from "../service/mercury";
import { ajv } from "./validators";
import { isContractId, isPubKey } from "../helper/validate";
import { Conf } from "../config";

const API_VERSION = "v1";
const NETWORK = "TESTNET"; // hardcode testnet for now, not sure how Mercury will change the schema for multi-network support yet

export function initApiServer(mercuryClient: MercuryClient, config: Conf) {
let redis = undefined;
if (config.mode !== "development") {
redis = new Redis({
connectionName: config.redisConnectionName,
host: config.hostname,
port: config.redisPort,
connectTimeout: 500,
maxRetriesPerRequest: 1,
});
}

export function initApiServer(
mercuryClient: MercuryClient,
logger: Logger,
redis?: Redis
) {
const server = Fastify({
logger: true,
logger,
});
server.setValidatorCompiler(({ schema }) => {
return ajv.compile(schema);
Expand Down Expand Up @@ -100,7 +94,8 @@ export function initApiServer(mercuryClient: MercuryClient, config: Conf) {
const contractIds = request.query["contract_ids"].split(",");
const { data, error } = await mercuryClient.getAccountBalances(
pubKey,
contractIds
contractIds,
NETWORK
);
if (error) {
reply.code(400).send(error);
Expand Down Expand Up @@ -213,7 +208,8 @@ export function initApiServer(mercuryClient: MercuryClient, config: Conf) {
const { pub_key, contract_id } = request.body;
const { data, error } = await mercuryClient.tokenBalanceSubscription(
contract_id,
pub_key
pub_key,
NETWORK
);
if (error) {
reply.code(400).send(error);
Expand Down
36 changes: 36 additions & 0 deletions src/service/mercury/helpers/transformers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { OperationResult } from "@urql/core";

// Transformers take an API response, and transform it/augment it for frontend consumption

interface MercuryAccountBalancesData {
entryUpdateByContractIdAndKey: {
nodes: {
contractId: string;
keyXdr: string;
valueXdr: string;
}[];
};
}

interface TokenDetails {
[k: string]: {
name: string;
symbol: string;
decimals: string;
};
}

const transformAccountBalances = async (
rawResponse: OperationResult<MercuryAccountBalancesData>,
tokenDetails: TokenDetails
) => {
return rawResponse?.data?.entryUpdateByContractIdAndKey.nodes.map((entry) => {
const details = tokenDetails[entry.contractId];
return {
...entry,
...details,
};
});
};

export { transformAccountBalances };
9 changes: 4 additions & 5 deletions src/service/mercury/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,13 @@ describe("Mercury Service", () => {
"CCWAMYJME4H5CKG7OLXGC2T4M6FL52XCZ3OQOAV6LL3GLA4RO4WH3ASP",
"CBGTG7XFRY3L6OKAUTR6KGDKUXUQBX3YDJ3QFDYTGVMOM7VV4O7NCODG",
];
const { data } = await mockMercuryClient.getAccountBalances(
const data = await mockMercuryClient.getAccountBalances(
pubKey,
contracts
contracts,
"TESTNET"
);
expect(
data?.data.edges.map(
(node: { node: Record<string, string> }) => node.node.contractId
)
data?.data?.map((node: { contractId: string }) => node.contractId)
).toEqual(contracts);
});

Expand Down
Loading
Loading