Skip to content

Commit

Permalink
refactor!: core type for address string reprensetation 'Address' rena…
Browse files Browse the repository at this point in the history
…med to PaymentAddress
  • Loading branch information
AngelCastilloB committed Mar 2, 2023
1 parent 23bdb6e commit 4287463
Show file tree
Hide file tree
Showing 68 changed files with 218 additions and 215 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ describe('utxoHttpProvider', () => {
await expect(
provider.utxoByAddresses({
addresses: [
Cardano.Address(
Cardano.PaymentAddress(
'addr_test1qretqkqqvc4dax3482tpjdazrfl8exey274m3mzch3dv8lu476aeq3kd8q8splpsswcfmv4y370e8r76rc8lnnhte49qqyjmtc'
)
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export const mapTxIn = (txIn: TxInput): Cardano.HydratedTxIn => ({
});

export const mapTxInModel = (txInModel: TxInputModel): TxInput => ({
address: txInModel.address as unknown as Cardano.Address,
address: txInModel.address as unknown as Cardano.PaymentAddress,
id: txInModel.id,
index: txInModel.index,
txInputId: txInModel.tx_input_id.toString('hex') as unknown as Cardano.TransactionId,
Expand All @@ -83,7 +83,7 @@ export const mapTxOut = (txOut: TxOutput): Cardano.TxOut => ({
});

export const mapTxOutModel = (txOutModel: TxOutputModel, assets?: Cardano.TokenMap): TxOutput => ({
address: txOutModel.address as unknown as Cardano.Address,
address: txOutModel.address as unknown as Cardano.PaymentAddress,
datumHash: txOutModel.datum ? (txOutModel.datum.toString('hex') as unknown as Hash32ByteBase16) : undefined,
index: txOutModel.index,
txId: txOutModel.tx_id.toString('hex') as unknown as Cardano.TransactionId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export interface TxInputModel {
}

export interface TxInput {
address: Cardano.Address;
address: Cardano.PaymentAddress;
id: string;
index: number;
txInputId: Cardano.TransactionId;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export class UtxoBuilder {
this.#db = db;
this.#logger = logger;
}
public async utxoByAddresses(addresses: Cardano.Address[]): Promise<Cardano.Utxo[]> {
public async utxoByAddresses(addresses: Cardano.PaymentAddress[]): Promise<Cardano.Utxo[]> {
this.#logger.debug('About to find utxos of addresses ', addresses);
const result: QueryResult<UtxoModel> = await this.#db.query(findUtxosByAddresses, [addresses]);
return result.rows.length > 0 ? utxosToCore(result.rows) : [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export const utxosToCore = (utxosModels: UtxoModel[]): Cardano.Utxo[] => {
}
utxos.set(utxoId, [txIn, txOut]);
} else {
const address = current.address as unknown as Cardano.Address;
const address = current.address as unknown as Cardano.PaymentAddress;
const txOut: Cardano.TxOut = {
address,
value: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -389,11 +389,11 @@ describe('ChainHistoryHttpService', () => {
const response = await provider.transactionsByAddresses({ addresses, pagination });

expect(response.pageResults.length).toEqual(5);
expect(() => Cardano.Address(addresses[0] as unknown as string)).not.toThrow();
expect(() => Cardano.PaymentAddress(addresses[0] as unknown as string)).not.toThrow();
});

it('does not include transactions not found', async () => {
const unknownAddress = Cardano.Address(
const unknownAddress = Cardano.PaymentAddress(
'addr_test1qrrmuxkfgytnf2lhlx2qhg8uz276747cnduyqpjutqac4qydra7fr0rzkg800zmk29x6tg92yqp7mnvmt42ruqgg5vjsncz9rt'
);
const response = await provider.transactionsByAddresses({
Expand Down Expand Up @@ -425,7 +425,7 @@ describe('ChainHistoryHttpService', () => {

expect(response.totalResultCount).toEqual(txInRangeCount);
expect(lowerBound).toBeGreaterThanOrEqual(10);
expect(() => Cardano.Address([...addresses][0] as unknown as string)).not.toThrow();
expect(() => Cardano.PaymentAddress([...addresses][0] as unknown as string)).not.toThrow();
for (const tx of response.pageResults) expect(tx.blockHeader).toMatchShapeOf(DataMocks.Tx.blockHeader);
});

Expand Down Expand Up @@ -507,8 +507,8 @@ describe('ChainHistoryHttpService', () => {

describe('finds transactions of given addresses', () => {
it('finds transactions with address within inputs', async () => {
const genesisAddresses: Cardano.Address[] = await fixtureBuilder.getDistinctAddresses(3);
const addresses: Cardano.Address[] = [genesisAddresses[0]];
const genesisAddresses: Cardano.PaymentAddress[] = await fixtureBuilder.getDistinctAddresses(3);
const addresses: Cardano.PaymentAddress[] = [genesisAddresses[0]];
const response = await provider.transactionsByAddresses({ addresses, pagination: { limit: 5, startAt: 0 } });
expect(response.pageResults.length).toBeGreaterThan(0);
expect(
Expand All @@ -518,8 +518,8 @@ describe('ChainHistoryHttpService', () => {
});

it('finds transactions with address within outputs', async () => {
const addresses: Cardano.Address[] = await fixtureBuilder.getGenesisAddresses();
expect(() => Cardano.Address(addresses[0] as unknown as string)).not.toThrow();
const addresses: Cardano.PaymentAddress[] = await fixtureBuilder.getGenesisAddresses();
expect(() => Cardano.PaymentAddress(addresses[0] as unknown as string)).not.toThrow();

const firstPageResponse = await provider.transactionsByAddresses({
addresses,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ const baseCertModel: CertificateModel = {
};

const txInput: TxInput = {
address: Cardano.Address(address),
address: Cardano.PaymentAddress(address),
id: '1',
index: 1,
txInputId: Cardano.TransactionId(transactionHash),
Expand All @@ -65,7 +65,7 @@ const txInputModel: TxInputModel = {
};

const txOutput: TxOutput = {
address: Cardano.Address(address),
address: Cardano.PaymentAddress(address),
datumHash: Hash32ByteBase16(hash32ByteBase16),
index: 1,
txId: Cardano.TransactionId(transactionHash),
Expand Down Expand Up @@ -300,9 +300,11 @@ describe('chain history mappers', () => {
});
describe('mapTxAlonzo', () => {
const inputs: Cardano.HydratedTxIn[] = [
{ address: Cardano.Address(address), index: 1, txId: Cardano.TransactionId(transactionHash) }
{ address: Cardano.PaymentAddress(address), index: 1, txId: Cardano.TransactionId(transactionHash) }
];
const outputs: Cardano.TxOut[] = [
{ address: Cardano.PaymentAddress(address), value: { assets, coins: 20_000_000n } }
];
const outputs: Cardano.TxOut[] = [{ address: Cardano.Address(address), value: { assets, coins: 20_000_000n } }];
const redeemers: Cardano.Redeemer[] = [
{
data: HexBlob(hash28ByteBase16),
Expand Down Expand Up @@ -367,7 +369,7 @@ describe('chain history mappers', () => {
test('map txInputModel to TxInput', () => {
const result = mappers.mapTxInModel(txInputModel);
expect(result).toEqual<TxInput>({
address: Cardano.Address(txInputModel.address),
address: Cardano.PaymentAddress(txInputModel.address),
id: txInputModel.id,
index: txInputModel.index,
txInputId: Cardano.TransactionId(transactionHash),
Expand All @@ -379,7 +381,7 @@ describe('chain history mappers', () => {
test('map TxInput to Cardano.HydratedTxIn', () => {
const result = mappers.mapTxIn(txInput);
expect(result).toEqual<Cardano.HydratedTxIn>({
address: Cardano.Address(address),
address: Cardano.PaymentAddress(address),
index: 1,
txId: Cardano.TransactionId(sourceTransactionHash)
});
Expand All @@ -389,7 +391,7 @@ describe('chain history mappers', () => {
test('map TxOutputModel with assets to TxOutput', () => {
const result = mappers.mapTxOutModel(txOutModel, assets);
expect(result).toEqual<TxOutput>({
address: Cardano.Address(address),
address: Cardano.PaymentAddress(address),
datumHash: Hash32ByteBase16(hash32ByteBase16),
index: 1,
txId: Cardano.TransactionId(transactionHash),
Expand All @@ -399,7 +401,7 @@ describe('chain history mappers', () => {
test('map TxOutputModel with no assets to TxOutput', () => {
const result = mappers.mapTxOutModel(txOutModel);
expect(result).toEqual<TxOutput>({
address: Cardano.Address(address),
address: Cardano.PaymentAddress(address),
datumHash: Hash32ByteBase16(hash32ByteBase16),
index: 1,
txId: Cardano.TransactionId(transactionHash),
Expand All @@ -409,7 +411,7 @@ describe('chain history mappers', () => {
test('map TxOutputModel with nulls to TxOutput', () => {
const result = mappers.mapTxOutModel({ ...txOutModel, datum: null });
expect(result).toEqual<TxOutput>({
address: Cardano.Address(address),
address: Cardano.PaymentAddress(address),
index: 1,
txId: Cardano.TransactionId(transactionHash),
value: { coins: 20_000_000n }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export enum TxWith {
}

export type AddressesInBlockRange = {
addresses: Set<Cardano.Address>;
addresses: Set<Cardano.PaymentAddress>;
blockRange: Range<Cardano.BlockNo>;
txInRangeCount: number;
};
Expand All @@ -43,7 +43,7 @@ export class ChainHistoryFixtureBuilder {
const upperBound = blockRange?.upperBound ?? DB_MAX_SAFE_INTEGER;
const txIds = new Set<bigint>();
const addressesInBlockRange = {
addresses: new Set<Cardano.Address>(),
addresses: new Set<Cardano.PaymentAddress>(),
blockRange: { lowerBound: Cardano.BlockNo(DB_MAX_SAFE_INTEGER), upperBound: Cardano.BlockNo(0) },
txInRangeCount: 0
};
Expand All @@ -62,15 +62,15 @@ export class ChainHistoryFixtureBuilder {
for (const { address } of results.rows) {
if (addressesInBlockRange.addresses.size >= desiredQty) break;

addressesInBlockRange.addresses.add(address as unknown as Cardano.Address);
addressesInBlockRange.addresses.add(address as unknown as Cardano.PaymentAddress);
}

if (results.rows.length < desiredQty) {
this.#logger.warn(`${desiredQty} addresses desired, only ${results.rows.length} results found`);
}

for (const { address, block_no, tx_id } of results.rows) {
if (addressesInBlockRange.addresses.has(address as unknown as Cardano.Address)) {
if (addressesInBlockRange.addresses.has(address as unknown as Cardano.PaymentAddress)) {
txIds.add(tx_id);
addressesInBlockRange.blockRange.lowerBound = Cardano.BlockNo(
Math.min(addressesInBlockRange.blockRange.lowerBound, block_no)
Expand Down Expand Up @@ -144,10 +144,10 @@ export class ChainHistoryFixtureBuilder {
public async getGenesisAddresses() {
this.#logger.debug('About to fetch genesis addresses');
const result: QueryResult<{ address: string }> = await this.#db.query(Queries.genesisUtxoAddresses);
return result.rows.map(({ address }) => address as unknown as Cardano.Address);
return result.rows.map(({ address }) => address as unknown as Cardano.PaymentAddress);
}

public async getDistinctAddresses(desiredQty: number): Promise<Cardano.Address[]> {
public async getDistinctAddresses(desiredQty: number): Promise<Cardano.PaymentAddress[]> {
this.#logger.debug(`About to fetch up to the last ${desiredQty} distinct addresses`);
const result: QueryResult<{ address: string }> = await this.#db.query(Queries.latestDistinctAddresses, [
desiredQty
Expand All @@ -158,6 +158,6 @@ export class ChainHistoryFixtureBuilder {
} else if (resultsQty < desiredQty) {
this.#logger.warn(`${desiredQty} distinct addresses desired, only ${resultsQty} results found`);
}
return result.rows.map(({ address }) => address as unknown as Cardano.Address);
return result.rows.map(({ address }) => address as unknown as Cardano.PaymentAddress);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ describe('utxosToCore', () => {
expect(utxosToCore(someFetchedUtxos)).toEqual([
[
{
address: Cardano.Address(
address: Cardano.PaymentAddress(
'addr_test1qpcnmvyjmxmsm75f747u566gw7ewz4mesdw7yl278uf9r3f5l7d7dpx2ymfwlm3e56flupga8yamjr2kwdt7dw77ktyqqtx2r7'
),
index: 1,
txId: Cardano.TransactionId('8fd14baca91c674fafae59701b7dc0eda1266202ec8445bad3244bd8669a7fb5')
},
{
address: Cardano.Address(
address: Cardano.PaymentAddress(
'addr_test1qpcnmvyjmxmsm75f747u566gw7ewz4mesdw7yl278uf9r3f5l7d7dpx2ymfwlm3e56flupga8yamjr2kwdt7dw77ktyqqtx2r7'
),
value: {
Expand All @@ -52,14 +52,14 @@ describe('utxosToCore', () => {
).toEqual([
[
{
address: Cardano.Address(
address: Cardano.PaymentAddress(
'addr_test1qpcnmvyjmxmsm75f747u566gw7ewz4mesdw7yl278uf9r3f5l7d7dpx2ymfwlm3e56flupga8yamjr2kwdt7dw77ktyqqtx2r7'
),
index: 1,
txId: Cardano.TransactionId('8fd14baca91c674fafae59701b7dc0eda1266202ec8445bad3244bd8669a7fb5')
},
{
address: Cardano.Address(
address: Cardano.PaymentAddress(
'addr_test1qpcnmvyjmxmsm75f747u566gw7ewz4mesdw7yl278uf9r3f5l7d7dpx2ymfwlm3e56flupga8yamjr2kwdt7dw77ktyqqtx2r7'
),
value: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ describe('UtxoHttpService', () => {

expect(res.length).toBeGreaterThan(0);
expect(res[0]).toMatchShapeOf([DataMocks.Tx.input, DataMocks.Tx.output]);
expect(() => Cardano.Address(addresses[0] as unknown as string)).not.toThrow();
expect(() => Cardano.PaymentAddress(addresses[0] as unknown as string)).not.toThrow();
});

it('return UTxO with inline datum', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export class UtxoFixtureBuilder {
public async getAddresses(
desiredQty: number,
options?: { with?: AddressWith[]; scriptType?: string }
): Promise<Cardano.Address[]> {
): Promise<Cardano.PaymentAddress[]> {
this.#logger.debug(`About to fetch up to ${desiredQty} addresses`);

let result: QueryResult<{ address: string }>;
Expand Down Expand Up @@ -54,6 +54,6 @@ export class UtxoFixtureBuilder {
this.#logger.warn(`${desiredQty} distinct addresses desired, only ${resultsQty} results found`);
}

return result!.rows.map(({ address }) => address as unknown as Cardano.Address);
return result!.rows.map(({ address }) => address as unknown as Cardano.PaymentAddress);
}
}
4 changes: 2 additions & 2 deletions packages/cardano-services/test/data-mocks/tx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const valueWithAssets: Cardano.Value = {
};

export const txOutBase: Omit<Cardano.TxOut, 'value' | 'datum'> = {
address: Cardano.Address('addr_test1wrsexavz37208qda7mwwu4k7hcpg26cz0ce86f5e9kul3hqzlh22t')
address: Cardano.PaymentAddress('addr_test1wrsexavz37208qda7mwwu4k7hcpg26cz0ce86f5e9kul3hqzlh22t')
};

export const txOutBaseWithDatum: Omit<Cardano.TxOut, 'value'> = {
Expand All @@ -28,7 +28,7 @@ export const txOutWithCoinOnly: Cardano.TxOut = { ...txOutBase, value: valueWith
export const txOutWithAssets: Cardano.TxOut = { ...txOutBase, value: valueWithAssets };

export const txIn: Cardano.HydratedTxIn = {
address: Cardano.Address('addr_test1wrsexavz37208qda7mwwu4k7hcpg26cz0ce86f5e9kul3hqzlh22t'),
address: Cardano.PaymentAddress('addr_test1wrsexavz37208qda7mwwu4k7hcpg26cz0ce86f5e9kul3hqzlh22t'),
index: 0,
txId: Cardano.TransactionId('cefd2fcf657e5e5d6c35975f4e052f427819391b153ebb16ad8aa107ba5a3819')
};
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/CML/address.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import * as Crypto from '@cardano-sdk/crypto';
import { Address, NetworkId, RewardAccount } from '../Cardano';
import { CML } from './CML';
import { NetworkId, PaymentAddress, RewardAccount } from '../Cardano';
import { parseCmlAddress } from './parseCmlAddress';
import { usingAutoFree } from '@cardano-sdk/util';

export const addressNetworkId = (address: RewardAccount | Address): NetworkId =>
export const addressNetworkId = (address: RewardAccount | PaymentAddress): NetworkId =>
usingAutoFree((scope) => parseCmlAddress(scope, address)!.network_id());

export const createRewardAccount = (stakeKeyHash: Crypto.Ed25519KeyHashHex, networkId: NetworkId) =>
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/CML/cmlToCore/cmlToCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ export const txOut = (output: CML.TransactionOutput): Cardano.TxOut =>
const address = byronAddress ? byronAddress.to_base58() : cmlAddress.to_bech32();

return {
address: Cardano.Address(address),
address: Cardano.PaymentAddress(address),
datum: inlineDatum ? bytesToHex(inlineDatum) : undefined,
datumHash: dataHashBytes ? Crypto.Hash32ByteBase16.fromHexBlob(bytesToHex(dataHashBytes)) : undefined,
scriptReference: scriptRef ? getCoreScript(scope, scope.manage(scriptRef.script())) : undefined,
Expand Down
16 changes: 8 additions & 8 deletions packages/core/src/Cardano/types/Address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ import { isAddress } from '../util/address';
/**
* mainnet or testnet address (Shelley as bech32 string, Byron as base58-encoded string)
*/
export type Address = OpaqueString<'Address'>;
export type PaymentAddress = OpaqueString<'Address'>;

/**
* @param {string} value mainnet or testnet address
* @param {string} address mainnet or testnet address
* @throws InvalidStringError
*/

Expand All @@ -28,19 +28,19 @@ const isRewardAccount = (address: string) => {
};

/**
* Transform a `value` into `Cardano.Address`,
* Resulting Address will be base58 in case of Byron era or bech32 in case of Shelley era or newer.
* Transform a `value` into `Cardano.PaymentAddress`,
* Resulting PaymentAddress will be base58 in case of Byron era or bech32 in case of Shelley era or newer.
*
* @param value bech32 string, base58 string or hex-encoded bytes address.
* @throws {InvalidStringError} if value is invalid
*/

export const Address = (value: string): Address => {
export const PaymentAddress = (value: string): PaymentAddress => {
if (isAddress(value)) {
if (isRewardAccount(value)) {
throw new InvalidStringError(value, 'Address type can only be used for payment addresses');
}
return value as unknown as Address;
return value as unknown as PaymentAddress;
}

try {
Expand All @@ -51,10 +51,10 @@ export const Address = (value: string): Address => {

return usingAutoFree((scope) => {
try {
return Address(scope.manage(CML.ByronAddress.from_bytes(Buffer.from(value, 'hex'))).to_base58());
return PaymentAddress(scope.manage(CML.ByronAddress.from_bytes(Buffer.from(value, 'hex'))).to_base58());
} catch {
try {
return Address(scope.manage(CML.Address.from_bytes(Buffer.from(value, 'hex'))).to_bech32());
return PaymentAddress(scope.manage(CML.Address.from_bytes(Buffer.from(value, 'hex'))).to_bech32());
} catch {
throw new InvalidStringError(value, 'Invalid payment address');
}
Expand Down
Loading

0 comments on commit 4287463

Please sign in to comment.