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(wallet): added a new input resolver decorator that also fetches from the backend #1082

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
8 changes: 6 additions & 2 deletions packages/core/src/Cardano/Address/PaymentAddress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
assertIsBech32WithPrefix,
assertIsHexString
} from '@cardano-sdk/util';
import { HydratedTx, HydratedTxIn, TxIn, TxOut } from '../types';
import { HydratedTx, HydratedTxIn, Tx, TxIn, TxOut } from '../types';
import { NetworkId } from '../ChainId';
import { RewardAccount } from './RewardAccount';

Expand Down Expand Up @@ -68,11 +68,15 @@ export const isAddressWithin =
export const inputsWithAddresses = (tx: HydratedTx, ownAddresses: PaymentAddress[]): HydratedTxIn[] =>
tx.body.inputs.filter(isAddressWithin(ownAddresses));

export type ResolveOptions = {
hints: Tx[];
};

/**
* @param txIn transaction input to resolve associated txOut from
* @returns txOut
*/
export type ResolveInput = (txIn: TxIn) => Promise<TxOut | null>;
export type ResolveInput = (txIn: TxIn, options?: ResolveOptions) => Promise<TxOut | null>;

export interface InputResolver {
resolveInput: ResolveInput;
Expand Down
76 changes: 72 additions & 4 deletions packages/wallet/src/services/WalletUtil.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable no-bitwise */
import * as Crypto from '@cardano-sdk/crypto';
import { Cardano } from '@cardano-sdk/core';
import { Cardano, ChainHistoryProvider } from '@cardano-sdk/core';
import { GroupedAddress, util as KeyManagementUtil } from '@cardano-sdk/key-management';
import { Observable, firstValueFrom } from 'rxjs';
import { ObservableWallet, ScriptAddress, isScriptAddress } from '../types';
Expand All @@ -23,11 +23,79 @@ export interface WalletOutputValidatorContext {
export type WalletUtilContext = WalletOutputValidatorContext & InputResolverContext;

export const createInputResolver = ({ utxo }: InputResolverContext): Cardano.InputResolver => ({
async resolveInput(input: Cardano.TxIn) {
async resolveInput(input: Cardano.TxIn, options?: Cardano.ResolveOptions) {
const utxoAvailable = await firstValueFrom(utxo.available$);
const availableUtxo = utxoAvailable?.find(([txIn]) => txInEquals(txIn, input));
if (!availableUtxo) return null;
return availableUtxo[1];

if (availableUtxo) return availableUtxo[1];

if (options?.hints) {
const tx = options?.hints.find((hint) => hint.id === input.txId);

if (tx && tx.body.outputs.length > input.index) {
return tx.body.outputs[input.index];
}
}
return null;
}
});

/**
* Creates an input resolver that fetch transaction inputs from the backend.
*
* This function tries to fetch the transaction from the backend using a `ChainHistoryProvider`. It
* also caches fetched transactions to optimize subsequent input resolutions.
*
* @param provider The backend provider used to fetch transactions by their hashes if
* they are not found by the inputResolver.
* @returns An input resolver that can fetch unresolved inputs from the backend.
*/
export const createBackendInputResolver = (provider: ChainHistoryProvider): Cardano.InputResolver => {
const txCache = new Map<Cardano.TransactionId, Cardano.Tx>();

const fetchAndCacheTransaction = async (txId: Cardano.TransactionId): Promise<Cardano.Tx | null> => {
if (txCache.has(txId)) {
return txCache.get(txId)!;
}

const txs = await provider.transactionsByHashes({ ids: [txId] });
if (txs.length > 0) {
txCache.set(txId, txs[0]);
return txs[0];
}

return null;
};

return {
async resolveInput(input: Cardano.TxIn, options?: Cardano.ResolveOptions) {
// Add hints to the cache
if (options?.hints) {
for (const hint of options.hints) {
txCache.set(hint.id, hint);
}
}

const tx = await fetchAndCacheTransaction(input.txId);
if (!tx) return null;

return tx.body.outputs.length > input.index ? tx.body.outputs[input.index] : null;
}
};
};

/**
* Combines multiple input resolvers into a single resolver.
*
* @param resolvers The input resolvers to combine.
*/
export const combineInputResolvers = (...resolvers: Cardano.InputResolver[]): Cardano.InputResolver => ({
async resolveInput(txIn: Cardano.TxIn, options?: Cardano.ResolveOptions) {
for (const resolver of resolvers) {
const resolved = await resolver.resolveInput(txIn, options);
if (resolved) return resolved;
}
return null;
}
});

Expand Down
Loading