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

[LW-10504]add timeout transaction inspectors #1313

Merged
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
1 change: 1 addition & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"@cardano-ogmios/schema": "6.3.0",
"@cardano-sdk/crypto": "workspace:~",
"@cardano-sdk/util": "workspace:~",
"@cardano-sdk/util-dev": "workspace:~",
"@foxglove/crc": "^0.0.3",
"@scure/base": "^1.1.1",
"fraction.js": "4.0.1",
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/Asset/types/AssetInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,12 @@ export interface AssetInfo {
name: AssetName;
fingerprint: AssetFingerprint;
/**
* `0n` if not loaded
*
* @deprecated Use `supply` instead
*/
quantity: bigint;
/** `0n` if not loaded */
supply: bigint;
/** CIP-0035. `undefined` if not loaded, `null` if no metadata found */
tokenMetadata?: TokenMetadata | null;
Expand Down
6 changes: 6 additions & 0 deletions packages/core/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,9 @@ export class NotImplementedError extends CustomError {
super(`Not implemented: ${missingFeature}`);
}
}

export class TimeoutError extends CustomError {
public constructor(message: string) {
super(`Timeout: ${message}`);
}
}
17 changes: 17 additions & 0 deletions packages/core/src/util/promiseTimeout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/* eslint-disable promise/param-names */

import { TimeoutError } from '../errors';

export const promiseTimeout = <T>(promise: Promise<T>, timeout: number) => {
let timeoutId: NodeJS.Timeout;

return Promise.race([
promise,
new Promise<T>(
(_, reject) =>
(timeoutId = setTimeout(() => reject(new TimeoutError('Failed to resolve the promise in time')), timeout))
)
]).finally(() => {
if (timeoutId) clearTimeout(timeoutId);
});
};
66 changes: 55 additions & 11 deletions packages/core/src/util/tokenTransferInspector.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
/* eslint-disable promise/param-names */
import * as Cardano from '../Cardano';
import { AssetInfo } from '../Asset';
import { AssetProvider } from '../Provider';
import { Inspector, resolveInputs } from './txInspector';
import { Inspector, ResolutionResult, resolveInputs } from './txInspector';
import { Logger } from 'ts-log';
import { Milliseconds } from './time';
import { TimeoutError } from '../errors';
import { coalesceValueQuantities } from './coalesceValueQuantities';
import { promiseTimeout } from './promiseTimeout';
import { subtractValueQuantities } from './subtractValueQuantities';
import { tryGetAssetInfos } from './tryGetAssetInfos';
import uniq from 'lodash/uniq.js';

export type AssetInfoWithAmount = { amount: Cardano.Lovelace; assetInfo: AssetInfo };
Expand All @@ -28,10 +34,23 @@ export interface TokenTransferInspectorArgs {

/** The asset provider to resolve AssetInfo for assets in the toAddress field. */
toAddressAssetProvider: AssetProvider;

/** Timeout provided by the app that consumes the inspector to personalise the UI response */
timeout: Milliseconds;

/** logger */
logger: Logger;
}

export type TokenTransferInspector = (args: TokenTransferInspectorArgs) => Inspector<TokenTransferInspection>;

type IntoTokenTransferValueProps = {
addressMap: Map<Cardano.PaymentAddress, Cardano.Value>;
assetProvider: AssetProvider;
timeout: Milliseconds;
logger: Logger;
};

const coalesceByAddress = <T extends { address: Cardano.PaymentAddress; value: Cardano.Value }>(
elements: T[]
): Map<Cardano.PaymentAddress, Cardano.Value> => {
Expand Down Expand Up @@ -116,10 +135,12 @@ const removeZeroBalanceEntries = (addressMap: Map<Cardano.PaymentAddress, Cardan
}
};

const toTokenTransferValue = async (
assetProvider: AssetProvider,
addressMap: Map<Cardano.PaymentAddress, Cardano.Value>
): Promise<Map<Cardano.PaymentAddress, TokenTransferValue>> => {
const intoTokenTransferValue = async ({
logger,
assetProvider,
timeout,
addressMap
}: IntoTokenTransferValueProps): Promise<Map<Cardano.PaymentAddress, TokenTransferValue>> => {
const tokenTransferValue = new Map<Cardano.PaymentAddress, TokenTransferValue>();

for (const [address, value] of addressMap.entries()) {
Expand All @@ -128,9 +149,11 @@ const toTokenTransferValue = async (
const assetInfos = new Map<Cardano.AssetId, AssetInfoWithAmount>();

if (assetIds.length > 0) {
const assets = await assetProvider.getAssets({
const assets = await tryGetAssetInfos({
assetIds,
extraData: { nftMetadata: true, tokenMetadata: true }
assetProvider,
logger,
timeout
});

for (const asset of assets) {
Expand All @@ -150,9 +173,20 @@ const toTokenTransferValue = async (

/** Inspect a transaction and return a map of addresses and their balances. */
export const tokenTransferInspector: TokenTransferInspector =
({ inputResolver, fromAddressAssetProvider, toAddressAssetProvider }) =>
({ inputResolver, fromAddressAssetProvider, toAddressAssetProvider, timeout, logger }) =>
async (tx) => {
const { resolvedInputs } = await resolveInputs(tx.body.inputs, inputResolver);
let resolvedInputs: ResolutionResult['resolvedInputs'];

try {
const inputResolution = await promiseTimeout(resolveInputs(tx.body.inputs, inputResolver), timeout);
resolvedInputs = inputResolution.resolvedInputs;
} catch (error) {
if (error instanceof TimeoutError) {
logger.error('Error: Inputs resolution timed out');
}

resolvedInputs = [];
}

const coalescedInputsByAddress = coalesceByAddress(resolvedInputs);
const coalescedOutputsByAddress = coalesceByAddress(tx.body.outputs);
Expand All @@ -168,7 +202,17 @@ export const tokenTransferInspector: TokenTransferInspector =
removeZeroBalanceEntries(toAddress);

return {
fromAddress: await toTokenTransferValue(fromAddressAssetProvider, fromAddress),
toAddress: await toTokenTransferValue(toAddressAssetProvider, toAddress)
fromAddress: await intoTokenTransferValue({
addressMap: fromAddress,
assetProvider: fromAddressAssetProvider,
logger,
timeout
}),
toAddress: await intoTokenTransferValue({
addressMap: toAddress,
assetProvider: toAddressAssetProvider,
logger,
timeout
})
};
};
66 changes: 56 additions & 10 deletions packages/core/src/util/transactionSummaryInspector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,15 @@ import {
totalAddressOutputsValueInspector
} from './txInspector';
import { BigIntMath } from '@cardano-sdk/util';
import { Logger } from 'ts-log';
import { Milliseconds } from './time';
import { TimeoutError } from '../errors';
import { coalesceTokenMaps, subtractTokenMaps } from '../Asset/util';
import { coalesceValueQuantities } from './coalesceValueQuantities';
import { computeImplicitCoin } from '../Cardano/util';
import { promiseTimeout } from './promiseTimeout';
import { subtractValueQuantities } from './subtractValueQuantities';
import { tryGetAssetInfos } from './tryGetAssetInfos';

interface TransactionSummaryInspectorArgs {
addresses: Cardano.PaymentAddress[];
Expand All @@ -26,6 +31,8 @@ interface TransactionSummaryInspectorArgs {
protocolParameters: Cardano.ProtocolParameters;
assetProvider: AssetProvider;
dRepKeyHash?: Crypto.Ed25519KeyHashHex;
timeout: Milliseconds;
logger: Logger;
}

export type TransactionSummaryInspection = {
Expand All @@ -45,6 +52,13 @@ export type TransactionSummaryInspector = (
args: TransactionSummaryInspectorArgs
) => Inspector<TransactionSummaryInspection>;

type IntoTokenTransferValueProps = {
assetProvider: AssetProvider;
logger: Logger;
timeout: Milliseconds;
tokenMap?: TokenMap;
};

/**
* Gets the collateral specified for this transaction.
*
Expand Down Expand Up @@ -116,19 +130,23 @@ const getUnaccountedFunds = async (
return subtractValueQuantities([totalOutputs, totalInputs]);
};

const toAssetInfoWithAmount = async (
assetProvider: AssetProvider,
tokenMap?: TokenMap
): Promise<Map<Cardano.AssetId, AssetInfoWithAmount>> => {
const intoAssetInfoWithAmount = async ({
assetProvider,
logger,
timeout,
tokenMap
}: IntoTokenTransferValueProps): Promise<Map<Cardano.AssetId, AssetInfoWithAmount>> => {
if (!tokenMap) return new Map();

const assetIds = tokenMap && tokenMap.size > 0 ? [...tokenMap.keys()] : [];
const assetInfos = new Map<Cardano.AssetId, AssetInfoWithAmount>();

if (assetIds.length > 0) {
const assets = await assetProvider.getAssets({
const assets = await tryGetAssetInfos({
assetIds,
extraData: { nftMetadata: true, tokenMetadata: true }
assetProvider,
logger,
timeout
});

for (const asset of assets) {
Expand All @@ -146,9 +164,32 @@ const toAssetInfoWithAmount = async (
* @param {TransactionSummaryInspectorArgs} args The arguments for the inspector.
*/
export const transactionSummaryInspector: TransactionSummaryInspector =
(args: TransactionSummaryInspectorArgs) => async (tx) => {
const { inputResolver, addresses, rewardAccounts, protocolParameters, assetProvider, dRepKeyHash } = args;
const resolvedInputs = await resolveInputs(tx.body.inputs, inputResolver);
({
inputResolver,
addresses,
rewardAccounts,
protocolParameters,
assetProvider,
dRepKeyHash,
timeout,
logger
}: TransactionSummaryInspectorArgs) =>
async (tx) => {
let resolvedInputs: ResolutionResult;

try {
resolvedInputs = await promiseTimeout(resolveInputs(tx.body.inputs, inputResolver), timeout);
} catch (error) {
if (error instanceof TimeoutError) {
logger.error('Error: Inputs resolution timed out');
}

resolvedInputs = {
resolvedInputs: [],
unresolvedInputs: tx.body.inputs
};
}

const fee = tx.body.fee;

const implicit = computeImplicitCoin(
Expand All @@ -171,7 +212,12 @@ export const transactionSummaryInspector: TransactionSummaryInspector =
};

return {
assets: await toAssetInfoWithAmount(assetProvider, diff.assets),
assets: await intoAssetInfoWithAmount({
assetProvider,
logger,
timeout,
tokenMap: diff.assets
}),
coins: diff.coins,
collateral,
deposit: implicit.deposit || 0n,
Expand Down
41 changes: 41 additions & 0 deletions packages/core/src/util/tryGetAssetInfos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import * as Cardano from '../Cardano';
import { AssetInfo } from '../Asset';
import { AssetProvider } from '../Provider';
import { Logger } from 'ts-log';
import { Milliseconds } from './time';
import { promiseTimeout } from './promiseTimeout';

type TryGetAssetInfosProps = {
assetIds: Cardano.AssetId[];
assetProvider: AssetProvider;
timeout: Milliseconds;
logger: Logger;
};

export const tryGetAssetInfos = async ({ assetIds, assetProvider, logger, timeout }: TryGetAssetInfosProps) => {
try {
return await promiseTimeout(
assetProvider.getAssets({
assetIds,
extraData: { nftMetadata: true, tokenMetadata: true }
}),
timeout
);
} catch (error) {
logger.error('Error: Failed to retrieve assets', error);

return assetIds.map<AssetInfo>((assetId) => {
const policyId = Cardano.AssetId.getPolicyId(assetId);
const name = Cardano.AssetId.getAssetName(assetId);

return {
assetId,
fingerprint: Cardano.AssetFingerprint.fromParts(policyId, name),
name,
policyId,
quantity: 0n,
supply: 0n
};
});
}
};
26 changes: 26 additions & 0 deletions packages/core/test/util/mocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import * as Cardano from '../../src/Cardano';
import { Asset, AssetProvider, HealthCheckResponse } from '../../src';

export const createMockInputResolver = (
historicalTxs: Cardano.HydratedTx[],
resolveDelay = 0
): Cardano.InputResolver => ({
async resolveInput(input: Cardano.TxIn) {
const tx = historicalTxs.find((historicalTx) => historicalTx.id === input.txId);

if (!tx || tx.body.outputs.length <= input.index) return Promise.resolve(null);

return await new Promise((resolve) => {
setTimeout(() => {
resolve(tx.body.outputs[input.index]);
}, resolveDelay);
});
}
});

export const createMockAssetProvider = (assets: Asset.AssetInfo[]): AssetProvider => ({
getAsset: async ({ assetId }) =>
assets.find((asset) => asset.assetId === assetId) ?? Promise.reject('Asset not found'),
getAssets: async ({ assetIds }) => assets.filter((asset) => assetIds.includes(asset.assetId)),
healthCheck: async () => Promise.resolve({} as HealthCheckResponse)
});
Loading
Loading