diff --git a/.eslintrc.js b/.eslintrc.js index 9549dff3a54..ca29d576b0c 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -9,7 +9,7 @@ module.exports = { "plugin:@typescript-eslint/recommended", "plugin:jsdoc/recommended" ], - "plugins": ["jsdoc"], + "plugins": ["jsdoc", "sort-keys-fix", "sort-imports-es6-autofix"], "settings": { "import/resolver": { "typescript": {} @@ -27,6 +27,9 @@ module.exports = { "no-unused-expressions": 0, "no-useless-constructor": 0, "quotes": ["error", "single", { "avoidEscape": true }], + "sort-keys-fix/sort-keys-fix": ["warn", "asc", {"natural": true}], + "sort-imports-es6-autofix/sort-imports-es6": "warn", + "sort-imports": ["warn", {ignoreDeclarationSort: true}], "unicorn/filename-case": 0, "unicorn/prevent-abbreviations": 0, "unicorn/no-null": 0, diff --git a/package.json b/package.json index e1ccc079ac0..ef24f25c560 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "docs": "typedoc --packages . && yarn workspaces run coverage && node collectCoverage.mjs", "cleanup": "yarn workspaces run cleanup && shx rm -rf node_modules", "lint": "yarn workspaces run lint", + "lint:fix": "yarn workspaces run lint:fix", "tscNoEmit": "yarn workspaces run tscNoEmit", "prepare": "husky install", "pre-commit": "lint-staged", @@ -65,6 +66,8 @@ "eslint-plugin-prettier": "^3.4.0", "eslint-plugin-promise": "^5.1.0", "eslint-plugin-sonarjs": "^0.9.1", + "eslint-plugin-sort-imports-es6-autofix": "^0.6.0", + "eslint-plugin-sort-keys-fix": "^1.1.2", "eslint-plugin-unicorn": "^35.0.0", "eslint-watch": "^7.0.0", "fs-extra": "^10.0.0", diff --git a/packages/blockfrost/package.json b/packages/blockfrost/package.json index 43933a63dcf..512691357a8 100644 --- a/packages/blockfrost/package.json +++ b/packages/blockfrost/package.json @@ -15,6 +15,7 @@ "tscNoEmit": "shx echo typescript --noEmit command not implemented yet", "cleanup": "shx rm -rf dist node_modules", "lint": "eslint --ignore-path ../../.eslintignore \"**/*.ts\"", + "lint:fix": "eslint --fix --ignore-path ../../.eslintignore \"**/*.ts\"", "test": "jest -c ./jest.config.js", "coverage": "shx echo No coverage report for this package", "prepack": "yarn build" diff --git a/packages/blockfrost/src/BlockfrostToCore.ts b/packages/blockfrost/src/BlockfrostToCore.ts index 5bf7f6e85a5..22f3ef52235 100644 --- a/packages/blockfrost/src/BlockfrostToCore.ts +++ b/packages/blockfrost/src/BlockfrostToCore.ts @@ -1,5 +1,5 @@ -import { Responses } from '@blockfrost/blockfrost-js'; import { Cardano, ProtocolParametersRequiredByWallet } from '@cardano-sdk/core'; +import { Responses } from '@blockfrost/blockfrost-js'; type Unpacked = T extends (infer U)[] ? U : T; type BlockfrostAddressUtxoContent = Responses['address_utxo_content']; @@ -15,21 +15,28 @@ export const BlockfrostToCore = { BlockfrostToCore.txIn(BlockfrostToCore.inputFromUtxo(address, utxo)), BlockfrostToCore.txOut(BlockfrostToCore.outputFromUtxo(address, utxo)) ]) as Cardano.Utxo[], - // without `as OgmiosSchema.Utxo` above TS thinks the return value is (OgmiosSchema.TxIn | OgmiosSchema.TxOut)[][] - transactionUtxos: (utxoResponse: Responses['tx_content_utxo']) => ({ - inputs: utxoResponse.inputs.map((input) => ({ - ...BlockfrostToCore.txIn(input), - address: input.address - })), - outputs: utxoResponse.outputs.map(BlockfrostToCore.txOut) - }), blockToTip: (block: Responses['block_content']): Cardano.Tip => ({ blockNo: block.height!, hash: block.hash, slot: block.slot! }), + currentWalletProtocolParameters: ( + blockfrost: Responses['epoch_param_content'] + ): ProtocolParametersRequiredByWallet => ({ + coinsPerUtxoWord: Number(blockfrost.coins_per_utxo_word), + maxCollateralInputs: blockfrost.max_collateral_inputs || undefined, + maxTxSize: Number(blockfrost.max_tx_size), + maxValueSize: Number(blockfrost.max_val_size), + minFeeCoefficient: blockfrost.min_fee_a, + minFeeConstant: blockfrost.min_fee_b, + minPoolCost: Number(blockfrost.min_pool_cost), + poolDeposit: Number(blockfrost.pool_deposit), + protocolVersion: { major: blockfrost.protocol_major_ver, minor: blockfrost.protocol_minor_ver }, + stakeKeyDeposit: Number(blockfrost.key_deposit) + }), + inputFromUtxo: (address: string, utxo: BlockfrostUtxo): BlockfrostInput => ({ address, amount: utxo.amount, @@ -46,16 +53,25 @@ export const BlockfrostToCore = { outputs: (outputs: BlockfrostOutputs): Cardano.TxOut[] => outputs.map((output) => BlockfrostToCore.txOut(output)), + // without `as OgmiosSchema.Utxo` above TS thinks the return value is (OgmiosSchema.TxIn | OgmiosSchema.TxOut)[][] + transactionUtxos: (utxoResponse: Responses['tx_content_utxo']) => ({ + inputs: utxoResponse.inputs.map((input) => ({ + ...BlockfrostToCore.txIn(input), + address: input.address + })), + outputs: utxoResponse.outputs.map(BlockfrostToCore.txOut) + }), + txContentUtxo: (blockfrost: Responses['tx_content_utxo']) => ({ + hash: blockfrost.hash, inputs: BlockfrostToCore.inputs(blockfrost.inputs), - outputs: BlockfrostToCore.outputs(blockfrost.outputs), - hash: blockfrost.hash + outputs: BlockfrostToCore.outputs(blockfrost.outputs) }), txIn: (blockfrost: BlockfrostInput): Cardano.TxIn => ({ - txId: blockfrost.tx_hash, + address: blockfrost.address, index: blockfrost.output_index, - address: blockfrost.address + txId: blockfrost.tx_hash }), txOut: (blockfrost: BlockfrostOutput): Cardano.TxOut => { @@ -67,24 +83,9 @@ export const BlockfrostToCore = { return { address: blockfrost.address, value: { - coins: BigInt(blockfrost.amount.find(({ unit }) => unit === 'lovelace')!.quantity), - assets + assets, + coins: BigInt(blockfrost.amount.find(({ unit }) => unit === 'lovelace')!.quantity) } }; - }, - - currentWalletProtocolParameters: ( - blockfrost: Responses['epoch_param_content'] - ): ProtocolParametersRequiredByWallet => ({ - maxTxSize: Number(blockfrost.max_tx_size), - minFeeCoefficient: blockfrost.min_fee_a, - minFeeConstant: blockfrost.min_fee_b, - stakeKeyDeposit: Number(blockfrost.key_deposit), - poolDeposit: Number(blockfrost.pool_deposit), - minPoolCost: Number(blockfrost.min_pool_cost), - coinsPerUtxoWord: Number(blockfrost.coins_per_utxo_word), - maxValueSize: Number(blockfrost.max_val_size), - maxCollateralInputs: blockfrost.max_collateral_inputs || undefined, - protocolVersion: { major: blockfrost.protocol_major_ver, minor: blockfrost.protocol_minor_ver } - }) + } }; diff --git a/packages/blockfrost/src/blockfrostProvider.ts b/packages/blockfrost/src/blockfrostProvider.ts index e2c566c884e..a10f7511978 100644 --- a/packages/blockfrost/src/blockfrostProvider.ts +++ b/packages/blockfrost/src/blockfrostProvider.ts @@ -1,8 +1,8 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import { WalletProvider, ProviderError, ProviderFailure, Cardano } from '@cardano-sdk/core'; import { BlockFrostAPI, Error as BlockfrostError, Responses } from '@blockfrost/blockfrost-js'; -import { Options } from '@blockfrost/blockfrost-js/lib/types'; import { BlockfrostToCore } from './BlockfrostToCore'; +import { Cardano, ProviderError, ProviderFailure, WalletProvider } from '@cardano-sdk/core'; +import { Options } from '@blockfrost/blockfrost-js/lib/types'; import { dummyLogger } from 'ts-log'; const formatBlockfrostError = (error: unknown) => { @@ -32,9 +32,9 @@ const formatBlockfrostError = (error: unknown) => { throw new ProviderError(ProviderFailure.Unknown, error, 'failed to parse error (status code)'); } return { - status_code, + error: errorAsType2.errno.toString(), message: errorAsType1.message, - error: errorAsType2.errno.toString() + status_code }; } throw new ProviderError(ProviderFailure.Unknown, error, 'failed to parse error (response json)'); @@ -127,7 +127,7 @@ export const blockfrostProvider = (options: Options, logger = dummyLogger): Wall rewards: BigInt(accountResponse.withdrawable_amount) }; - return { utxo, delegationAndRewards }; + return { delegationAndRewards, utxo }; }; const fetchRedeemers = async ({ @@ -138,11 +138,11 @@ export const blockfrostProvider = (options: Options, logger = dummyLogger): Wall const response = await blockfrost.txsRedeemers(hash); return response.map( ({ purpose, script_hash, unit_mem, unit_steps, tx_index }): Cardano.Redeemer => ({ - index: tx_index, executionUnits: { memory: Number.parseInt(unit_mem), steps: Number.parseInt(unit_steps) }, + index: tx_index, purpose: ((): Cardano.Redeemer['purpose'] => { switch (purpose) { case 'cert': @@ -184,8 +184,8 @@ export const blockfrostProvider = (options: Options, logger = dummyLogger): Wall const fetchPoolRetireCerts = async (hash: string): Promise => { const response = await blockfrost.txsPoolRetires(hash); return response.map(({ cert_index, pool_id, retiring_epoch }) => ({ - epoch: retiring_epoch, certIndex: cert_index, + epoch: retiring_epoch, poolId: pool_id, type: Cardano.CertificateType.PoolRetirement })); @@ -194,8 +194,8 @@ export const blockfrostProvider = (options: Options, logger = dummyLogger): Wall const fetchPoolUpdateCerts = async (hash: string): Promise => { const response = await blockfrost.txsPoolUpdates(hash); return response.map(({ cert_index, pool_id, active_epoch }) => ({ - epoch: active_epoch, certIndex: cert_index, + epoch: active_epoch, poolId: pool_id, type: Cardano.CertificateType.PoolRegistration })); @@ -204,32 +204,32 @@ export const blockfrostProvider = (options: Options, logger = dummyLogger): Wall const fetchMirCerts = async (hash: string): Promise => { const response = await blockfrost.txsMirs(hash); return response.map(({ address, amount, cert_index, pot }) => ({ - type: Cardano.CertificateType.MIR, address, - quantity: BigInt(amount), certIndex: cert_index, - pot + pot, + quantity: BigInt(amount), + type: Cardano.CertificateType.MIR })); }; const fetchStakeCerts = async (hash: string): Promise => { const response = await blockfrost.txsStakes(hash); return response.map(({ address, cert_index, registration }) => ({ - type: registration ? Cardano.CertificateType.StakeRegistration : Cardano.CertificateType.StakeDeregistration, address, - certIndex: cert_index + certIndex: cert_index, + type: registration ? Cardano.CertificateType.StakeRegistration : Cardano.CertificateType.StakeDeregistration })); }; const fetchDelegationCerts = async (hash: string): Promise => { const response = await blockfrost.txsDelegations(hash); return response.map(({ cert_index, index, address, active_epoch, pool_id }) => ({ - type: Cardano.CertificateType.StakeDelegation, + address, certIndex: cert_index, delegationIndex: index, - address, epoch: active_epoch, - poolId: pool_id + poolId: pool_id, + type: Cardano.CertificateType.StakeDelegation })); }; @@ -257,30 +257,30 @@ export const blockfrostProvider = (options: Options, logger = dummyLogger): Wall const { inputs, outputs } = BlockfrostToCore.transactionUtxos(await blockfrost.txsUtxos(hash)); const response = await blockfrost.txs(hash); return { - id: hash, blockHeader: { - slot: response.slot, + blockHash: response.block, blockHeight: response.block_height, - blockHash: response.block - }, - txSize: response.size, - implicitCoin: { - deposit: BigInt(response.deposit) - // TODO: use computeImplicitCoin to compute implicit input + slot: response.slot }, body: { + certificates: await fetchCertificates(response), + fee: BigInt(response.fees), index: response.index, inputs, + mint: await fetchMint(response), outputs, - fee: BigInt(response.fees), validityInterval: { invalidBefore: parseValidityInterval(response.invalid_before), invalidHereafter: parseValidityInterval(response.invalid_hereafter) }, - withdrawals: await fetchWithdrawals(response), - mint: await fetchMint(response), - certificates: await fetchCertificates(response) + withdrawals: await fetchWithdrawals(response) }, + id: hash, + implicitCoin: { + deposit: BigInt(response.deposit) + // TODO: use computeImplicitCoin to compute implicit input + }, + txSize: response.size, witness: { redeemers: await fetchRedeemers(response) } @@ -314,14 +314,14 @@ export const blockfrostProvider = (options: Options, logger = dummyLogger): Wall }; const providerFunctions: WalletProvider = { + currentWalletProtocolParameters, ledgerTip, networkInfo, - stakePoolStats, - submitTx, - utxoDelegationAndRewards, queryTransactionsByAddresses, queryTransactionsByHashes, - currentWalletProtocolParameters + stakePoolStats, + submitTx, + utxoDelegationAndRewards }; return Object.keys(providerFunctions).reduce((provider, key) => { diff --git a/packages/blockfrost/test/blockfrostProvider.test.ts b/packages/blockfrost/test/blockfrostProvider.test.ts index f591dc93655..690fc664188 100644 --- a/packages/blockfrost/test/blockfrostProvider.test.ts +++ b/packages/blockfrost/test/blockfrostProvider.test.ts @@ -2,8 +2,8 @@ /* eslint-disable max-len */ import { BlockFrostAPI, Responses } from '@blockfrost/blockfrost-js'; -import { blockfrostProvider } from '../src'; import { Cardano, NetworkInfo, StakePoolStats } from '@cardano-sdk/core'; +import { blockfrostProvider } from '../src'; jest.mock('@blockfrost/blockfrost-js'); const generatePoolsResponseMock = (qty: number) => @@ -14,35 +14,35 @@ describe('blockfrostProvider', () => { test('networkInfo', async () => { const mockedEpochsLatestResponse = { - epoch: 158, - start_time: 1_632_255_616, + active_stake: '1060378314781343', + block_count: 9593, end_time: 1_632_687_616, + epoch: 158, + fees: '4426764732', first_block_time: 1_632_255_656, last_block_time: 1_632_571_205, - block_count: 9593, - tx_count: 20_736, output: '10876219159738237', - fees: '4426764732', - active_stake: '1060378314781343' + start_time: 1_632_255_616, + tx_count: 20_736 } as Responses['epoch_content']; const mockedNetworkResponse = { stake: { - live: '15001884895856815', - active: '1060378314781343' + active: '1060378314781343', + live: '15001884895856815' }, supply: { - max: '45000000000000000', - total: '40267211394073980', circulating: '42064399450423723', - locked: '6161981104458' + locked: '6161981104458', + max: '45000000000000000', + total: '40267211394073980' } } as Responses['network']; BlockFrostAPI.prototype.epochsLatest = jest.fn().mockResolvedValue(mockedEpochsLatestResponse); BlockFrostAPI.prototype.network = jest.fn().mockResolvedValue(mockedNetworkResponse); - const client = blockfrostProvider({ projectId: apiKey, isTestnet: true }); + const client = blockfrostProvider({ isTestnet: true, projectId: apiKey }); const response = await client.networkInfo(); expect(response).toMatchObject({ @@ -88,7 +88,7 @@ describe('blockfrostProvider', () => { .mockReturnValueOnce(generatePoolsResponseMock(100)) .mockReturnValueOnce(generatePoolsResponseMock(77)); - const client = blockfrostProvider({ projectId: apiKey, isTestnet: true }); + const client = blockfrostProvider({ isTestnet: true, projectId: apiKey }); const response = await client.stakePoolStats!(); expect(response).toMatchObject({ @@ -103,51 +103,51 @@ describe('blockfrostProvider', () => { test('utxoDelegationAndRewards', async () => { const addressesUtxosAllMockResponse = [ { - tx_hash: '0f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5', - tx_index: 0, - output_index: 0, amount: [ { - unit: 'lovelace', - quantity: '50928877' + quantity: '50928877', + unit: 'lovelace' }, { - unit: 'b01fb3b8c3dd6b3705a5dc8bcd5a70759f70ad5d97a72005caeac3c652657675746f31333237', - quantity: '1' + quantity: '1', + unit: 'b01fb3b8c3dd6b3705a5dc8bcd5a70759f70ad5d97a72005caeac3c652657675746f31333237' } ], - block: 'b1b23210b9de8f3edef233f21f7d6e1fb93fe124ba126ba924edec3043e75b46' + block: 'b1b23210b9de8f3edef233f21f7d6e1fb93fe124ba126ba924edec3043e75b46', + output_index: 0, + tx_hash: '0f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5', + tx_index: 0 }, { - tx_hash: '6f04f2cd96b609b8d5675f89fe53159bab859fb1d62bb56c6001ccf58d9ac128', - tx_index: 0, - output_index: 0, amount: [ { - unit: 'lovelace', - quantity: '1097647' + quantity: '1097647', + unit: 'lovelace' } ], - block: '500de01367988d4698266ca02148bf2308eab96c0876c9df00ee843772ccb326' + block: '500de01367988d4698266ca02148bf2308eab96c0876c9df00ee843772ccb326', + output_index: 0, + tx_hash: '6f04f2cd96b609b8d5675f89fe53159bab859fb1d62bb56c6001ccf58d9ac128', + tx_index: 0 } ]; BlockFrostAPI.prototype.addressesUtxosAll = jest.fn().mockResolvedValue(addressesUtxosAllMockResponse); const accountsMockResponse = { - stake_address: 'stake_test1uqfu74w3wh4gfzu8m6e7j987h4lq9r3t7ef5gaw497uu85qsqfy27', active: true, active_epoch: 81, controlled_amount: '95565690389731', - rewards_sum: '615803862289', - withdrawals_sum: '0', + pool_id: 'pool1y6chk7x7fup4ms9leesdr57r4qy9cwxuee0msan72x976a6u0nc', reserves_sum: '0', + rewards_sum: '615803862289', + stake_address: 'stake_test1uqfu74w3wh4gfzu8m6e7j987h4lq9r3t7ef5gaw497uu85qsqfy27', treasury_sum: '0', withdrawable_amount: '615803862289', - pool_id: 'pool1y6chk7x7fup4ms9leesdr57r4qy9cwxuee0msan72x976a6u0nc' + withdrawals_sum: '0' }; BlockFrostAPI.prototype.accounts = jest.fn().mockResolvedValue(accountsMockResponse); - const client = blockfrostProvider({ projectId: apiKey, isTestnet: true }); + const client = blockfrostProvider({ isTestnet: true, projectId: apiKey }); const response = await client.utxoDelegationAndRewards( ['addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3jcu5d8ps7zex2k2xt3uqxgjqnnj83ws8lhrn648jjxtwq2ytjqp'], 'stake_test1uqfu74w3wh4gfzu8m6e7j987h4lq9r3t7ef5gaw497uu85qsqfy27' @@ -158,17 +158,17 @@ describe('blockfrostProvider', () => { expect(response.utxo[0][0]).toMatchObject({ address: 'addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3jcu5d8ps7zex2k2xt3uqxgjqnnj83ws8lhrn648jjxtwq2ytjqp', - txId: '0f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5', - index: 0 + index: 0, + txId: '0f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5' }); expect(response.utxo[0][1]).toMatchObject({ address: 'addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3jcu5d8ps7zex2k2xt3uqxgjqnnj83ws8lhrn648jjxtwq2ytjqp', value: { - coins: 50_928_877n, assets: { b01fb3b8c3dd6b3705a5dc8bcd5a70759f70ad5d97a72005caeac3c652657675746f31333237: BigInt(1) - } + }, + coins: 50_928_877n } }); @@ -176,15 +176,15 @@ describe('blockfrostProvider', () => { expect(response.utxo[1][0]).toMatchObject({ address: 'addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3jcu5d8ps7zex2k2xt3uqxgjqnnj83ws8lhrn648jjxtwq2ytjqp', - txId: '6f04f2cd96b609b8d5675f89fe53159bab859fb1d62bb56c6001ccf58d9ac128', - index: 0 + index: 0, + txId: '6f04f2cd96b609b8d5675f89fe53159bab859fb1d62bb56c6001ccf58d9ac128' }); expect(response.utxo[1][1]).toMatchObject({ address: 'addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3jcu5d8ps7zex2k2xt3uqxgjqnnj83ws8lhrn648jjxtwq2ytjqp', value: { - coins: 1_097_647n, - assets: {} + assets: {}, + coins: 1_097_647n } }); @@ -203,12 +203,12 @@ describe('blockfrostProvider', () => { 'addr_test1qr05llxkwg5t6c4j3ck5mqfax9wmz35rpcgw3qthrn9z7xcxu2hyfhlkwuxupa9d5085eunq2qywy7hvmvej456flknstdz3k2', amount: [ { - unit: 'lovelace', - quantity: '9732978705764' + quantity: '9732978705764', + unit: 'lovelace' } ], - tx_hash: '6d50c330a6fba79de6949a8dcd5e4b7ffa3f9442f0c5bed7a78fa6d786c6c863', - output_index: 1 + output_index: 1, + tx_hash: '6d50c330a6fba79de6949a8dcd5e4b7ffa3f9442f0c5bed7a78fa6d786c6c863' } ], outputs: [ @@ -217,16 +217,16 @@ describe('blockfrostProvider', () => { 'addr_test1qzx9hu8j4ah3auytk0mwcupd69hpc52t0cw39a65ndrah86djs784u92a3m5w475w3w35tyd6v3qumkze80j8a6h5tuqq5xe8y', amount: [ { - unit: 'lovelace', - quantity: '1000000000' + quantity: '1000000000', + unit: 'lovelace' }, { - unit: '06f8c5655b4e2b5911fee8ef2fc66b4ce64c8835642695c730a3d108617364', - quantity: '63' + quantity: '63', + unit: '06f8c5655b4e2b5911fee8ef2fc66b4ce64c8835642695c730a3d108617364' }, { - unit: '06f8c5655b4e2b5911fee8ef2fc66b4ce64c8835642695c730a3d108646464', - quantity: '22' + quantity: '22', + unit: '06f8c5655b4e2b5911fee8ef2fc66b4ce64c8835642695c730a3d108646464' } ] }, @@ -235,8 +235,8 @@ describe('blockfrostProvider', () => { 'addr_test1qra788mu4sg8kwd93ns9nfdh3k4ufxwg4xhz2r3n064tzfgxu2hyfhlkwuxupa9d5085eunq2qywy7hvmvej456flkns6cy45x', amount: [ { - unit: 'lovelace', - quantity: '9731978536963' + quantity: '9731978536963', + unit: 'lovelace' } ] } @@ -246,64 +246,59 @@ describe('blockfrostProvider', () => { it('without extra tx properties', async () => { const mockedResponse = { - hash: '1e043f100dce12d107f679685acd2fc0610e10f72a92d412794c9773d11d8477', + asset_mint_or_burn_count: 0, block: '356b7d7dbb696ccd12775c016941057a9dc70898d87a63fc752271bb46856940', block_height: 123_456, - slot: 42_000_000, + delegation_count: 0, + deposit: '5', + fees: '182485', + hash: '1e043f100dce12d107f679685acd2fc0610e10f72a92d412794c9773d11d8477', index: 1, + invalid_before: null, + invalid_hereafter: '13885913', + mir_cert_count: 0, output_amount: [ { - unit: 'lovelace', - quantity: '42000000' + quantity: '42000000', + unit: 'lovelace' }, { - unit: 'b0d07d45fe9514f80213f4020e5a61241458be626841cde717cb38a76e7574636f696e', - quantity: '12' + quantity: '12', + unit: 'b0d07d45fe9514f80213f4020e5a61241458be626841cde717cb38a76e7574636f696e' } ], - fees: '182485', - deposit: '5', - size: 433, - invalid_before: null, - invalid_hereafter: '13885913', - utxo_count: 2, - withdrawal_count: 0, - mir_cert_count: 0, - delegation_count: 0, - stake_cert_count: 0, - pool_update_count: 0, pool_retire_count: 0, - asset_mint_or_burn_count: 0, + pool_update_count: 0, redeemer_count: 0, - valid_contract: true + size: 433, + slot: 42_000_000, + stake_cert_count: 0, + utxo_count: 2, + valid_contract: true, + withdrawal_count: 0 }; BlockFrostAPI.prototype.txs = jest.fn().mockResolvedValue(mockedResponse) as any; - const client = blockfrostProvider({ projectId: apiKey, isTestnet: true }); + const client = blockfrostProvider({ isTestnet: true, projectId: apiKey }); const response = await client.queryTransactionsByHashes([ '4123d70f66414cc921f6ffc29a899aafc7137a99a0fd453d6b200863ef5702d6' ]); expect(response).toHaveLength(1); expect(response[0]).toMatchObject({ - id: '4123d70f66414cc921f6ffc29a899aafc7137a99a0fd453d6b200863ef5702d6', blockHeader: { - slot: 42_000_000, blockHash: '356b7d7dbb696ccd12775c016941057a9dc70898d87a63fc752271bb46856940', - blockHeight: 123_456 + blockHeight: 123_456, + slot: 42_000_000 }, - txSize: 433, body: { fee: 182_485n, index: 1, - validityInterval: { - invalidHereafter: 13_885_913 - }, inputs: [ { address: 'addr_test1qr05llxkwg5t6c4j3ck5mqfax9wmz35rpcgw3qthrn9z7xcxu2hyfhlkwuxupa9d5085eunq2qywy7hvmvej456flknstdz3k2', - txId: '6d50c330a6fba79de6949a8dcd5e4b7ffa3f9442f0c5bed7a78fa6d786c6c863', - index: 1 + index: 1, + txId: '6d50c330a6fba79de6949a8dcd5e4b7ffa3f9442f0c5bed7a78fa6d786c6c863' } ], outputs: [ @@ -311,26 +306,31 @@ describe('blockfrostProvider', () => { address: 'addr_test1qzx9hu8j4ah3auytk0mwcupd69hpc52t0cw39a65ndrah86djs784u92a3m5w475w3w35tyd6v3qumkze80j8a6h5tuqq5xe8y', value: { - coins: 1_000_000_000n, assets: { '06f8c5655b4e2b5911fee8ef2fc66b4ce64c8835642695c730a3d108617364': BigInt(63), '06f8c5655b4e2b5911fee8ef2fc66b4ce64c8835642695c730a3d108646464': BigInt(22) - } + }, + coins: 1_000_000_000n } }, { address: 'addr_test1qra788mu4sg8kwd93ns9nfdh3k4ufxwg4xhz2r3n064tzfgxu2hyfhlkwuxupa9d5085eunq2qywy7hvmvej456flkns6cy45x', value: { - coins: 9_731_978_536_963n, - assets: {} + assets: {}, + coins: 9_731_978_536_963n } } - ] + ], + validityInterval: { + invalidHereafter: 13_885_913 + } }, + id: '4123d70f66414cc921f6ffc29a899aafc7137a99a0fd453d6b200863ef5702d6', implicitCoin: { deposit: 5n - } + }, + txSize: 433 } as Cardano.TxAlonzo); }); it.todo('with withdrawals'); @@ -347,60 +347,60 @@ describe('blockfrostProvider', () => { test('currentWalletProtocolParameters', async () => { const mockedResponse = { data: { + coins_per_utxo_word: '0', + key_deposit: '2000000', + max_collateral_inputs: 1, + max_tx_size: '16384', + max_val_size: '1000', min_fee_a: 44, min_fee_b: 155_381, - key_deposit: '2000000', + min_pool_cost: '340000000', pool_deposit: '500000000', protocol_major_ver: 5, - protocol_minor_ver: 0, - min_pool_cost: '340000000', - max_tx_size: '16384', - max_val_size: '1000', - max_collateral_inputs: 1, - coins_per_utxo_word: '0' + protocol_minor_ver: 0 } }; BlockFrostAPI.prototype.axiosInstance = jest.fn().mockResolvedValue(mockedResponse) as any; - const client = blockfrostProvider({ projectId: apiKey, isTestnet: true }); + const client = blockfrostProvider({ isTestnet: true, projectId: apiKey }); const response = await client.currentWalletProtocolParameters(); expect(response).toMatchObject({ + coinsPerUtxoWord: 0, + maxCollateralInputs: 1, + maxTxSize: 16_384, + maxValueSize: 1000, minFeeCoefficient: 44, minFeeConstant: 155_381, - stakeKeyDeposit: 2_000_000, + minPoolCost: 340_000_000, poolDeposit: 500_000_000, protocolVersion: { major: 5, minor: 0 }, - minPoolCost: 340_000_000, - maxTxSize: 16_384, - maxValueSize: 1000, - maxCollateralInputs: 1, - coinsPerUtxoWord: 0 + stakeKeyDeposit: 2_000_000 }); }); test('ledgerTip', async () => { const mockedResponse = { - time: 1_632_136_410, - height: 2_927_618, - hash: '86e837d8a6cdfddaf364525ce9857eb93430b7e59a5fd776f0a9e11df476a7e5', - slot: 37_767_194, + block_vrf: 'vrf_vk19j362pkr4t9y0m3qxgmrv0365vd7c4ze03ny4jh84q8agjy4ep4s99zvg8', + confirmations: 0, epoch: 157, epoch_slot: 312_794, - slot_leader: 'pool1zuevzm3xlrhmwjw87ec38mzs02tlkwec9wxpgafcaykmwg7efhh', - size: 1050, - tx_count: 3, - output: '9249073880', fees: '513839', - block_vrf: 'vrf_vk19j362pkr4t9y0m3qxgmrv0365vd7c4ze03ny4jh84q8agjy4ep4s99zvg8', - previous_block: 'da56fa53483a3a087c893b41aa0d73a303148c2887b3f7535e0b505ea5dc10aa', + hash: '86e837d8a6cdfddaf364525ce9857eb93430b7e59a5fd776f0a9e11df476a7e5', + height: 2_927_618, next_block: null, - confirmations: 0 + output: '9249073880', + previous_block: 'da56fa53483a3a087c893b41aa0d73a303148c2887b3f7535e0b505ea5dc10aa', + size: 1050, + slot: 37_767_194, + slot_leader: 'pool1zuevzm3xlrhmwjw87ec38mzs02tlkwec9wxpgafcaykmwg7efhh', + time: 1_632_136_410, + tx_count: 3 } as Responses['block_content']; BlockFrostAPI.prototype.blocksLatest = jest.fn().mockResolvedValue(mockedResponse); - const client = blockfrostProvider({ projectId: apiKey, isTestnet: true }); + const client = blockfrostProvider({ isTestnet: true, projectId: apiKey }); const response = await client.ledgerTip(); expect(response).toMatchObject({ diff --git a/packages/cardano-graphql-db-sync/package.json b/packages/cardano-graphql-db-sync/package.json index b6ff61b2a00..5ba9eaa6f27 100644 --- a/packages/cardano-graphql-db-sync/package.json +++ b/packages/cardano-graphql-db-sync/package.json @@ -15,6 +15,7 @@ "tscNoEmit": "shx echo typescript --noEmit command not implemented yet", "cleanup": "shx rm -rf dist node_modules", "lint": "eslint --ignore-path ../../.eslintignore \"**/*.ts\"", + "lint:fix": "eslint --fix --ignore-path ../../.eslintignore \"**/*.ts\"", "test": "jest -c ./jest.config.js", "coverage": "shx echo No coverage report for this package", "prepack": "yarn build" diff --git a/packages/cardano-graphql-db-sync/src/CardanoGraphqlToCore.ts b/packages/cardano-graphql-db-sync/src/CardanoGraphqlToCore.ts index f026de972ce..0ef84c087f1 100644 --- a/packages/cardano-graphql-db-sync/src/CardanoGraphqlToCore.ts +++ b/packages/cardano-graphql-db-sync/src/CardanoGraphqlToCore.ts @@ -1,5 +1,5 @@ -import { ProtocolParametersRequiredByWallet, Cardano, NotImplementedError } from '@cardano-sdk/core'; import { Block } from '@cardano-graphql/client-ts'; +import { Cardano, NotImplementedError, ProtocolParametersRequiredByWallet } from '@cardano-sdk/core'; type GraphqlTransaction = { hash: Cardano.Hash16; @@ -43,21 +43,28 @@ export type TransactionsResponse = { }; const txIn = ({ sourceTxIndex, txHash, address }: GraphqlTransaction['inputs'][0]): Cardano.TxIn => ({ - txId: txHash, + address, index: sourceTxIndex, - address + txId: txHash }); const txOut = ({ address, tokens, value }: GraphqlTransaction['outputs'][0]) => { const assets: Cardano.Value['assets'] = {}; for (const token of tokens) assets[token.asset.assetId] = BigInt(token.quantity); - return { address, value: { coins: BigInt(value), assets } }; + return { address, value: { assets, coins: BigInt(value) } }; }; export const CardanoGraphqlToCore = { - txIn, - txOut, - + currentWalletProtocolParameters: ( + params: GraphqlCurrentWalletProtocolParameters + ): ProtocolParametersRequiredByWallet => ({ + ...params, + maxTxSize: params.maxTxSize, + maxValueSize: Number(params.maxValSize), + minFeeCoefficient: params.minFeeA, + minFeeConstant: params.minFeeB, + stakeKeyDeposit: params.keyDeposit + }), graphqlTransactionsToCardanoTxs: (_transactions: TransactionsResponse): Cardano.TxAlonzo[] => { // transactions.map((tx) => ({ // inputs: tx.inputs.map(txIn), @@ -67,20 +74,13 @@ export const CardanoGraphqlToCore = { throw new NotImplementedError('Need to query more data to support this'); }, - currentWalletProtocolParameters: ( - params: GraphqlCurrentWalletProtocolParameters - ): ProtocolParametersRequiredByWallet => ({ - ...params, - maxValueSize: Number(params.maxValSize), - stakeKeyDeposit: params.keyDeposit, - maxTxSize: params.maxTxSize, - minFeeCoefficient: params.minFeeA, - minFeeConstant: params.minFeeB - }), - tip: (tip: CardanoGraphQlTip): Cardano.Tip => ({ blockNo: tip.number!, hash: tip.hash, slot: tip.slotNo! - }) + }), + + txIn, + + txOut }; diff --git a/packages/cardano-graphql-db-sync/src/cardanoGraphqlDbSyncProvider.ts b/packages/cardano-graphql-db-sync/src/cardanoGraphqlDbSyncProvider.ts index 9361eecb735..b793729742e 100644 --- a/packages/cardano-graphql-db-sync/src/cardanoGraphqlDbSyncProvider.ts +++ b/packages/cardano-graphql-db-sync/src/cardanoGraphqlDbSyncProvider.ts @@ -1,13 +1,13 @@ -import { WalletProvider, ProviderError, ProviderFailure } from '@cardano-sdk/core'; -import { gql, GraphQLClient } from 'graphql-request'; -import { TransactionSubmitResponse } from '@cardano-graphql/client-ts'; import { Buffer } from 'buffer'; import { + CardanoGraphQlTip, CardanoGraphqlToCore, GraphqlCurrentWalletProtocolParameters, - CardanoGraphQlTip, TransactionsResponse } from './CardanoGraphqlToCore'; +import { GraphQLClient, gql } from 'graphql-request'; +import { ProviderError, ProviderFailure, WalletProvider } from '@cardano-sdk/core'; +import { TransactionSubmitResponse } from '@cardano-graphql/client-ts'; /** * Connect to a [cardano-graphql (cardano-db-sync) service](https://github.com/input-output-hk/cardano-graphql) @@ -336,13 +336,13 @@ export const cardanoGraphqlDbSyncProvider = (uri: string): WalletProvider => { }; return { + currentWalletProtocolParameters, ledgerTip, networkInfo, - stakePoolStats, - submitTx, - utxoDelegationAndRewards, queryTransactionsByAddresses, queryTransactionsByHashes, - currentWalletProtocolParameters + stakePoolStats, + submitTx, + utxoDelegationAndRewards }; }; diff --git a/packages/cardano-graphql-db-sync/test/cardanoGraphqlDbSyncProvider.test.ts b/packages/cardano-graphql-db-sync/test/cardanoGraphqlDbSyncProvider.test.ts index 86167107b7d..7bfce94e24c 100644 --- a/packages/cardano-graphql-db-sync/test/cardanoGraphqlDbSyncProvider.test.ts +++ b/packages/cardano-graphql-db-sync/test/cardanoGraphqlDbSyncProvider.test.ts @@ -1,7 +1,7 @@ /* eslint-disable max-len */ +import { Cardano, NetworkInfo, ProtocolParametersRequiredByWallet } from '@cardano-sdk/core'; import { GraphQLClient } from 'graphql-request'; -import { NetworkInfo, Cardano, ProtocolParametersRequiredByWallet } from '@cardano-sdk/core'; import { cardanoGraphqlDbSyncProvider } from '../src'; jest.mock('graphql-request'); @@ -112,10 +112,10 @@ describe('cardanoGraphqlDbSyncProvider', () => { currentEpoch: { protocolParams: { coinsPerUtxoWord: 34_482, - maxTxSize: 16_384, - maxValSize: '5000', keyDeposit: 2_000_000, maxCollateralInputs: 3, + maxTxSize: 16_384, + maxValSize: '5000', minFeeA: 44, minFeeB: 155_381, minPoolCost: 340_000_000, @@ -136,10 +136,9 @@ describe('cardanoGraphqlDbSyncProvider', () => { expect(response).toMatchObject({ coinsPerUtxoWord: 34_482, + maxCollateralInputs: 3, maxTxSize: 16_384, maxValueSize: 5000, - stakeKeyDeposit: 2_000_000, - maxCollateralInputs: 3, minFeeCoefficient: 44, minFeeConstant: 155_381, minPoolCost: 340_000_000, @@ -147,7 +146,8 @@ describe('cardanoGraphqlDbSyncProvider', () => { protocolVersion: { major: 5, minor: 5 - } + }, + stakeKeyDeposit: 2_000_000 }); }); @@ -168,8 +168,8 @@ describe('cardanoGraphqlDbSyncProvider', () => { const response = await client.ledgerTip(); expect(response).toMatchObject({ - hash: 'af310732fdd99892fa78584aca1d2be147e6001030ae51b054e38feeb4fd762d', blockNo: 2_884_196, + hash: 'af310732fdd99892fa78584aca1d2be147e6001030ae51b054e38feeb4fd762d', slot: 36_370_316 }); }); diff --git a/packages/cardano-graphql/package.json b/packages/cardano-graphql/package.json index 75b00a2905a..b4c42c5dc34 100644 --- a/packages/cardano-graphql/package.json +++ b/packages/cardano-graphql/package.json @@ -23,6 +23,7 @@ "tscNoEmit": "shx echo typescript --noEmit command not implemented yet", "cleanup": "shx rm -rf dist node_modules", "lint": "eslint --ignore-path ../../.eslintignore \"**/*.ts\"", + "lint:fix": "eslint --fix --ignore-path ../../.eslintignore \"**/*.ts\"", "test": "jest -c ./jest.config.js", "coverage": "yarn test --coverage", "prepack": "yarn build", diff --git a/packages/cardano-graphql/src/Schema/build.ts b/packages/cardano-graphql/src/Schema/build.ts index 7539ef493d3..6a27eada822 100644 --- a/packages/cardano-graphql/src/Schema/build.ts +++ b/packages/cardano-graphql/src/Schema/build.ts @@ -1,6 +1,6 @@ -import { GraphQLSchema } from 'graphql'; -import { Field, ObjectType, Query, Resolver, buildSchema } from 'type-graphql'; import * as types from './types'; +import { Field, ObjectType, Query, Resolver, buildSchema } from 'type-graphql'; +import { GraphQLSchema } from 'graphql'; @ObjectType() class Nothing { @@ -17,8 +17,8 @@ export class NothingResolver { export const build = async (): Promise => { const schema = await buildSchema({ - resolvers: [NothingResolver], - orphanedTypes: Object.values(types) + orphanedTypes: Object.values(types), + resolvers: [NothingResolver] }); const config = schema.toConfig(); config.types = config.types.filter(({ name }) => !['Query', 'Nothing'].includes(name)); diff --git a/packages/cardano-graphql/src/Schema/types/core/Cardano/ExtendedStakePoolMetadataFields.ts b/packages/cardano-graphql/src/Schema/types/core/Cardano/ExtendedStakePoolMetadataFields.ts index c1b7c7c0346..5454f7c6728 100644 --- a/packages/cardano-graphql/src/Schema/types/core/Cardano/ExtendedStakePoolMetadataFields.ts +++ b/packages/cardano-graphql/src/Schema/types/core/Cardano/ExtendedStakePoolMetadataFields.ts @@ -63,8 +63,8 @@ export class ExtendedStakePoolMetadataFields implements Cardano.ExtendedStakePoo @Field({ nullable: true }) country?: string; @Field(() => PoolStatus, { - nullable: true, - description: 'active | retired | offline | experimental | private' + description: 'active | retired | offline | experimental | private', + nullable: true }) status?: Cardano.PoolStatus; @Field(() => PoolContactData, { nullable: true }) diff --git a/packages/cardano-graphql/src/Schema/types/core/Cardano/StakePool.ts b/packages/cardano-graphql/src/Schema/types/core/Cardano/StakePool.ts index b135dff9ce0..8bc657e9aa5 100644 --- a/packages/cardano-graphql/src/Schema/types/core/Cardano/StakePool.ts +++ b/packages/cardano-graphql/src/Schema/types/core/Cardano/StakePool.ts @@ -1,7 +1,7 @@ /* eslint-disable no-use-before-define */ -import { Cardano } from '@cardano-sdk/core'; -import { createUnionType, Directive, Field, Float, Int, ObjectType } from 'type-graphql'; import { BigIntsAsStrings, coinDescription, percentageDescription } from '../../util'; +import { Cardano } from '@cardano-sdk/core'; +import { Directive, Field, Float, Int, ObjectType, createUnionType } from 'type-graphql'; import { ExtendedStakePoolMetadataFields } from './ExtendedStakePoolMetadataFields'; // This is not in ./ExtendedStakePoolMetadata to avoid circular import @@ -84,9 +84,11 @@ export class RelayByAddress implements Cardano.ByAddress { } const Relay = createUnionType({ - name: 'SearchResult', // the name of the GraphQL union - types: () => [RelayByName, RelayByAddress] as const, // function that returns tuple of object types classes, - resolveType: (value) => ('hostname' in value ? RelayByName : RelayByAddress) + name: 'SearchResult', + // function that returns tuple of object types classes, + resolveType: (value) => ('hostname' in value ? RelayByName : RelayByAddress), + // the name of the GraphQL union + types: () => [RelayByName, RelayByAddress] as const }); @ObjectType() diff --git a/packages/cardano-graphql/src/StakePoolSearchProvider/CardanoGraphQLStakePoolSearchProvider.ts b/packages/cardano-graphql/src/StakePoolSearchProvider/CardanoGraphQLStakePoolSearchProvider.ts index 9e97ca39f94..fb9c27e894a 100644 --- a/packages/cardano-graphql/src/StakePoolSearchProvider/CardanoGraphQLStakePoolSearchProvider.ts +++ b/packages/cardano-graphql/src/StakePoolSearchProvider/CardanoGraphQLStakePoolSearchProvider.ts @@ -1,4 +1,4 @@ -import { ProviderError, ProviderFailure, Cardano, StakePoolSearchProvider, util } from '@cardano-sdk/core'; +import { Cardano, ProviderError, ProviderFailure, StakePoolSearchProvider, util } from '@cardano-sdk/core'; import { GraphQLClient } from 'graphql-request'; import { getSdk } from '../sdk'; import { isNotNil } from '../util'; @@ -18,8 +18,8 @@ export const createGraphQLStakePoolSearchProvider = ( try { const byStakePoolFields = (await sdk.StakePools({ query })).queryStakePool?.filter(isNotNil); const byMetadataFields = await sdk.StakePoolsByMetadata({ - query, - omit: byStakePoolFields?.length ? byStakePoolFields?.map((sp) => sp.id) : undefined + omit: byStakePoolFields?.length ? byStakePoolFields?.map((sp) => sp.id) : undefined, + query }); const responseStakePools = [ ...(byStakePoolFields || []), @@ -31,15 +31,6 @@ export const createGraphQLStakePoolSearchProvider = ( const ext = metadata?.ext; return { ...stakePool, - pledge: BigInt(stakePool.pledge), - metrics: { - ...stakePool.metrics!, - livePledge: BigInt(stakePool.metrics.livePledge), - stake: { - active: BigInt(stakePool.metrics.stake.active), - live: BigInt(stakePool.metrics.stake.live) - } - }, cost: BigInt(stakePool.cost), metadata: metadata ? { @@ -54,7 +45,16 @@ export const createGraphQLStakePoolSearchProvider = ( } : undefined } - : undefined + : undefined, + metrics: { + ...stakePool.metrics!, + livePledge: BigInt(stakePool.metrics.livePledge), + stake: { + active: BigInt(stakePool.metrics.stake.active), + live: BigInt(stakePool.metrics.stake.live) + } + }, + pledge: BigInt(stakePool.pledge) }; }); } catch (error) { diff --git a/packages/cardano-graphql/test/StakePoolSearchProvider/CardanoGraphQLStakePoolSearchProvider.test.ts b/packages/cardano-graphql/test/StakePoolSearchProvider/CardanoGraphQLStakePoolSearchProvider.test.ts index b9494c784b3..a6357a5f8fb 100644 --- a/packages/cardano-graphql/test/StakePoolSearchProvider/CardanoGraphQLStakePoolSearchProvider.test.ts +++ b/packages/cardano-graphql/test/StakePoolSearchProvider/CardanoGraphQLStakePoolSearchProvider.test.ts @@ -1,6 +1,6 @@ /* eslint-disable max-len */ +import { PoolStatus, StakePoolsByMetadataQuery, StakePoolsQuery } from '../../src/sdk'; import { ProviderError, StakePoolSearchProvider } from '@cardano-sdk/core'; -import { StakePoolsQuery, StakePoolsByMetadataQuery, PoolStatus } from '../../src/sdk'; import { createGraphQLStakePoolSearchProvider } from '../../src/StakePoolSearchProvider/CardanoGraphQLStakePoolSearchProvider'; describe('StakePoolSearchClient', () => { @@ -22,30 +22,30 @@ describe('StakePoolSearchClient', () => { const stakePoolsQueryResponse: StakePoolsQuery = { queryStakePool: [ { - id: 'some-pool', - hexId: '0abc', cost: '123', + hexId: '0abc', + id: 'some-pool', margin: 0.15, - metadataJson: { - hash: '1abc', - url: 'http://someurl' - }, metadata: { description: 'some pool desc', - name: 'some pool', - homepage: 'http://homepage', - ticker: 'TICKR', - extDataUrl: 'http://extdata', - extSigUrl: 'http://extsig', - extVkey: '2abc', ext: { - serial: 123, pool: { + country: 'LT', id: 'pool-id', - status: PoolStatus.Active, - country: 'LT' - } - } + status: PoolStatus.Active + }, + serial: 123 + }, + extDataUrl: 'http://extdata', + extSigUrl: 'http://extsig', + extVkey: '2abc', + homepage: 'http://homepage', + name: 'some pool', + ticker: 'TICKR' + }, + metadataJson: { + hash: '1abc', + url: 'http://someurl' }, metrics: { blocksCreated: 123, @@ -63,16 +63,16 @@ describe('StakePoolSearchClient', () => { }, owners: ['5bd'], pledge: '1235', - vrf: '76bc', + relays: [ + { __typename: 'RelayByName', hostname: 'http://relay', port: 156 }, + { __typename: 'RelayByAddress', ipv4: '0.0.0.0', ipv6: '::1', port: 567 } + ], rewardAccount: '745b', transactions: { registration: ['6345b'], retirement: ['dawdb'] }, - relays: [ - { __typename: 'RelayByName', hostname: 'http://relay', port: 156 }, - { __typename: 'RelayByAddress', port: 567, ipv4: '0.0.0.0', ipv6: '::1' } - ] + vrf: '76bc' } ] }; @@ -92,8 +92,8 @@ describe('StakePoolSearchClient', () => { expect(response).toHaveLength(2); expect(sdk.StakePoolsByMetadata).toBeCalledWith({ - query: 'some stake pools', - omit: [stakePoolsQueryResponse.queryStakePool![0]!.id] + omit: [stakePoolsQueryResponse.queryStakePool![0]!.id], + query: 'some stake pools' }); expect(typeof response[0]).toBe('object'); expect(typeof response[0].cost).toBe('bigint'); diff --git a/packages/cip2/package.json b/packages/cip2/package.json index a12387bbbc8..66a3214e349 100644 --- a/packages/cip2/package.json +++ b/packages/cip2/package.json @@ -14,6 +14,7 @@ "tscNoEmit": "shx echo typescript --noEmit command not implemented yet", "cleanup": "shx rm -rf dist node_modules", "lint": "eslint --ignore-path ../../.eslintignore \"**/*.ts\"", + "lint:fix": "eslint --fix --ignore-path ../../.eslintignore \"**/*.ts\"", "test": "jest -c ./jest.config.js", "coverage": "yarn test --coverage", "prepack": "yarn build", diff --git a/packages/cip2/src/RoundRobinRandomImprove/change.ts b/packages/cip2/src/RoundRobinRandomImprove/change.ts index 8d670d699be..93e9ab7c2c1 100644 --- a/packages/cip2/src/RoundRobinRandomImprove/change.ts +++ b/packages/cip2/src/RoundRobinRandomImprove/change.ts @@ -1,16 +1,16 @@ import { CSL, Cardano, coreToCsl } from '@cardano-sdk/core'; -import { orderBy } from 'lodash-es'; import { ComputeMinimumCoinQuantity, TokenBundleSizeExceedsLimit } from '../types'; -import { InputSelectionError, InputSelectionFailure } from '../InputSelectionError'; import { + ImplicitCoinBigint, + UtxoSelection, + UtxoWithValue, assetQuantitySelector, assetWithValueQuantitySelector, getCoinQuantity, - getWithValuesCoinQuantity, - ImplicitCoinBigint, - UtxoSelection, - UtxoWithValue + getWithValuesCoinQuantity } from './util'; +import { InputSelectionError, InputSelectionFailure } from '../InputSelectionError'; +import { orderBy } from 'lodash-es'; type EstimateTxFeeWithOriginalOutputs = (utxo: CSL.TransactionUnspentOutput[], change: CSL.Value[]) => Promise; @@ -74,11 +74,11 @@ const redistributeLeftoverAssets = ( for (const [idx, quantity] of quantities.entries()) { const originalBundle = resultBundles[idx]; resultBundles.splice(idx, 1, { - coins: originalBundle.coins, assets: { ...originalBundle.assets, [assetId]: quantity - } + }, + coins: originalBundle.coins }); } } @@ -108,9 +108,9 @@ const createBundlePerOutput = ( totalAssetsBundled[assetId] = (totalAssetsBundled[assetId] || 0n) + assetChange; assets[assetId] = assetChange; } - return { coins, assets }; + return { assets, coins }; }); - return { totalCoinBundled, bundles, totalAssetsBundled }; + return { bundles, totalAssetsBundled, totalCoinBundled }; }; /** @@ -131,8 +131,8 @@ const computeRequestedAssetChangeBundles = ( const assetTotals: Record = {}; for (const assetId of uniqueOutputAssetIDs) { assetTotals[assetId] = { - selected: assetWithValueQuantitySelector(assetId)(utxoSelected), - requested: assetQuantitySelector(assetId)(outputValues) + requested: assetQuantitySelector(assetId)(outputValues), + selected: assetWithValueQuantitySelector(assetId)(utxoSelected) }; } const coinTotalSelected = getWithValuesCoinQuantity(utxoSelected) + implicitCoin.input; @@ -178,7 +178,7 @@ const pickExtraRandomUtxo = ({ utxoRemaining, utxoSelected }: UtxoSelection): Ut const newUtxoSelected = [...utxoSelected, pickFrom[pickIdx]]; const originalIdx = utxoRemaining.indexOf(pickFrom[pickIdx]); const newUtxoRemaining = [...utxoRemaining.slice(0, originalIdx), ...utxoRemaining.slice(originalIdx + 1)]; - return { utxoSelected: newUtxoSelected, utxoRemaining: newUtxoRemaining }; + return { utxoRemaining: newUtxoRemaining, utxoSelected: newUtxoSelected }; }; const coalesceChangeBundlesForMinCoinRequirement = ( @@ -245,12 +245,12 @@ const computeChangeBundles = ({ // Coalesced all bundles to 1 and it's still less than min utxo value if (utxoSelection.utxoRemaining.length > 0) { return computeChangeBundles({ - utxoSelection: pickExtraRandomUtxo(utxoSelection), + computeMinimumCoinQuantity, + fee, + implicitCoin, outputValues, uniqueOutputAssetIDs, - implicitCoin, - computeMinimumCoinQuantity, - fee + utxoSelection: pickExtraRandomUtxo(utxoSelection) }); } // This is not a great error type for this, because the spec says @@ -297,11 +297,11 @@ export const computeChangeAndAdjustForFee = async ({ utxoSelection }: ChangeComputationArgs): Promise => { const changeInclFee = computeChangeBundles({ - utxoSelection, + computeMinimumCoinQuantity, + implicitCoin, outputValues, uniqueOutputAssetIDs, - implicitCoin, - computeMinimumCoinQuantity + utxoSelection }); // Calculate fee with change outputs that include fee. @@ -322,28 +322,28 @@ export const computeChangeAndAdjustForFee = async ({ // Recompute change and fee with an extra selected UTxO return computeChangeAndAdjustForFee({ computeMinimumCoinQuantity, - tokenBundleSizeExceedsLimit, - outputValues, - uniqueOutputAssetIDs, estimateTxFee, implicitCoin, + outputValues, + tokenBundleSizeExceedsLimit, + uniqueOutputAssetIDs, utxoSelection: pickExtraRandomUtxo(changeInclFee) }); } const { changeBundles, utxoSelected, utxoRemaining } = computeChangeBundles({ - utxoSelection: { utxoRemaining: changeInclFee.utxoRemaining, utxoSelected: changeInclFee.utxoSelected }, + computeMinimumCoinQuantity, + fee, + implicitCoin, outputValues, uniqueOutputAssetIDs, - implicitCoin, - computeMinimumCoinQuantity, - fee + utxoSelection: { utxoRemaining: changeInclFee.utxoRemaining, utxoSelected: changeInclFee.utxoSelected } }); return { - remainingUTxO: utxoRemaining.map(({ utxo }) => utxo), - inputs: utxoSelected.map(({ utxo }) => utxo), change: changeBundlesToValues(changeBundles, tokenBundleSizeExceedsLimit), - fee + fee, + inputs: utxoSelected.map(({ utxo }) => utxo), + remainingUTxO: utxoRemaining.map(({ utxo }) => utxo) }; }; diff --git a/packages/cip2/src/RoundRobinRandomImprove/index.ts b/packages/cip2/src/RoundRobinRandomImprove/index.ts index 12895609d0b..f434d819a83 100644 --- a/packages/cip2/src/RoundRobinRandomImprove/index.ts +++ b/packages/cip2/src/RoundRobinRandomImprove/index.ts @@ -1,9 +1,9 @@ -import { cslUtil, CSL } from '@cardano-sdk/core'; +import { CSL, cslUtil } from '@cardano-sdk/core'; import { InputSelectionError, InputSelectionFailure } from '../InputSelectionError'; import { InputSelectionParameters, InputSelector, SelectionResult } from '../types'; +import { assertIsBalanceSufficient, preprocessArgs, withValuesToValues } from './util'; import { computeChangeAndAdjustForFee } from './change'; import { roundRobinSelection } from './roundRobin'; -import { assertIsBalanceSufficient, preprocessArgs, withValuesToValues } from './util'; export const roundRobinRandomImprove = (): InputSelector => ({ select: async ({ @@ -25,42 +25,42 @@ export const roundRobinRandomImprove = (): InputSelector => ({ const roundRobinSelectionResult = roundRobinSelection({ implicitCoin, outputsWithValue, - utxosWithValue, - uniqueOutputAssetIDs + uniqueOutputAssetIDs, + utxosWithValue }); const result = await computeChangeAndAdjustForFee({ computeMinimumCoinQuantity, - tokenBundleSizeExceedsLimit, - outputValues, - uniqueOutputAssetIDs, - implicitCoin, - utxoSelection: roundRobinSelectionResult, estimateTxFee: (utxos, changeValues) => computeMinimumCost({ - inputs: new Set(utxos), change: new Set(changeValues), fee: cslUtil.maxBigNum, + inputs: new Set(utxos), outputs - }) + }), + implicitCoin, + outputValues, + tokenBundleSizeExceedsLimit, + uniqueOutputAssetIDs, + utxoSelection: roundRobinSelectionResult }); const inputs = new Set(result.inputs); const change = new Set(result.change); const fee = CSL.BigNum.from_str(result.fee.toString()); - if (result.inputs.length > (await computeSelectionLimit({ inputs, change, fee, outputs }))) { + if (result.inputs.length > (await computeSelectionLimit({ change, fee, inputs, outputs }))) { throw new InputSelectionError(InputSelectionFailure.MaximumInputCountExceeded); } return { + remainingUTxO: new Set(result.remainingUTxO), selection: { change, + fee, inputs, - outputs, - fee - }, - remainingUTxO: new Set(result.remainingUTxO) + outputs + } }; } }); diff --git a/packages/cip2/src/RoundRobinRandomImprove/roundRobin.ts b/packages/cip2/src/RoundRobinRandomImprove/roundRobin.ts index cc6297963c7..1f83988c239 100644 --- a/packages/cip2/src/RoundRobinRandomImprove/roundRobin.ts +++ b/packages/cip2/src/RoundRobinRandomImprove/roundRobin.ts @@ -1,12 +1,12 @@ import { BigIntMath } from '@cardano-sdk/core'; import { - assetWithValueQuantitySelector, - getWithValuesCoinQuantity, + ImplicitCoinBigint, OutputWithValue, + RoundRobinRandomImproveArgs, UtxoSelection, UtxoWithValue, - RoundRobinRandomImproveArgs, - ImplicitCoinBigint + assetWithValueQuantitySelector, + getWithValuesCoinQuantity } from './util'; const improvesSelection = ( @@ -43,16 +43,16 @@ const listTokensWithin = ( ...uniqueOutputAssetIDs.map((id) => { const getQuantity = assetWithValueQuantitySelector(id); return { + filterUtxo: (utxo: UtxoWithValue[]) => utxo.filter(({ value: { assets } }) => assets?.[id]), getTotalSelectedQuantity: (utxo: UtxoWithValue[]) => getQuantity(utxo), - minimumTarget: getQuantity(outputs), - filterUtxo: (utxo: UtxoWithValue[]) => utxo.filter(({ value: { assets } }) => assets?.[id]) + minimumTarget: getQuantity(outputs) }; }), { + filterUtxo: (utxo: UtxoWithValue[]) => utxo, // Lovelace getTotalSelectedQuantity: (utxo: UtxoWithValue[]) => getWithValuesCoinQuantity(utxo) + implicitCoin.input, - minimumTarget: getWithValuesCoinQuantity(outputs) + implicitCoin.deposit, - filterUtxo: (utxo: UtxoWithValue[]) => utxo + minimumTarget: getWithValuesCoinQuantity(outputs) + implicitCoin.deposit } ]; @@ -105,5 +105,5 @@ export const roundRobinSelection = ({ } } } - return { utxoSelected, utxoRemaining }; + return { utxoRemaining, utxoSelected }; }; diff --git a/packages/cip2/src/RoundRobinRandomImprove/util.ts b/packages/cip2/src/RoundRobinRandomImprove/util.ts index aebf0679a91..b9c3e67a44d 100644 --- a/packages/cip2/src/RoundRobinRandomImprove/util.ts +++ b/packages/cip2/src/RoundRobinRandomImprove/util.ts @@ -1,6 +1,6 @@ -import { BigIntMath, Cardano, CSL, cslToCore } from '@cardano-sdk/core'; -import { uniq } from 'lodash-es'; +import { BigIntMath, CSL, Cardano, cslToCore } from '@cardano-sdk/core'; import { InputSelectionError, InputSelectionFailure } from '../InputSelectionError'; +import { uniq } from 'lodash-es'; export interface WithValue { value: Cardano.Value; @@ -56,7 +56,7 @@ export const preprocessArgs = ( deposit: partialImplicitCoin.deposit || 0n, input: partialImplicitCoin.input || 0n }; - return { uniqueOutputAssetIDs, utxosWithValue, outputsWithValue, implicitCoin }; + return { implicitCoin, outputsWithValue, uniqueOutputAssetIDs, utxosWithValue }; }; export const withValuesToValues = (totals: WithValue[]) => totals.map((t) => t.value); diff --git a/packages/cip2/src/selectionConstraints.ts b/packages/cip2/src/selectionConstraints.ts index f5d517ebb6e..731fafce676 100644 --- a/packages/cip2/src/selectionConstraints.ts +++ b/packages/cip2/src/selectionConstraints.ts @@ -1,14 +1,14 @@ -import { cslUtil, InvalidProtocolParametersError, CSL } from '@cardano-sdk/core'; -import { ProtocolParametersRequiredByInputSelection } from '.'; +import { CSL, InvalidProtocolParametersError, cslUtil } from '@cardano-sdk/core'; import { - TokenBundleSizeExceedsLimit, ComputeMinimumCoinQuantity, - EstimateTxFee, - SelectionSkeleton, ComputeSelectionLimit, + EstimateTxFee, ProtocolParametersForInputSelection, - SelectionConstraints + SelectionConstraints, + SelectionSkeleton, + TokenBundleSizeExceedsLimit } from './types'; +import { ProtocolParametersRequiredByInputSelection } from '.'; export type BuildTx = (selection: SelectionSkeleton) => Promise; @@ -90,8 +90,8 @@ export const defaultSelectionConstraints = ({ ); } return { - computeMinimumCost: computeMinimumCost({ minFeeCoefficient, minFeeConstant }, buildTx), computeMinimumCoinQuantity: computeMinimumCoinQuantity(coinsPerUtxoWord), + computeMinimumCost: computeMinimumCost({ minFeeCoefficient, minFeeConstant }, buildTx), computeSelectionLimit: computeSelectionLimit(maxTxSize, buildTx), tokenBundleSizeExceedsLimit: tokenBundleSizeExceedsLimit(maxValueSize) }; diff --git a/packages/cip2/src/types.ts b/packages/cip2/src/types.ts index df152461637..475ddbe7531 100644 --- a/packages/cip2/src/types.ts +++ b/packages/cip2/src/types.ts @@ -1,4 +1,4 @@ -import { Cardano, CSL } from '@cardano-sdk/core'; +import { CSL, Cardano } from '@cardano-sdk/core'; export interface SelectionSkeleton { /** diff --git a/packages/cip2/test/RoundRobinRandomImprove.test.ts b/packages/cip2/test/RoundRobinRandomImprove.test.ts index 1341d0c2f8e..fa1140e8611 100644 --- a/packages/cip2/test/RoundRobinRandomImprove.test.ts +++ b/packages/cip2/test/RoundRobinRandomImprove.test.ts @@ -1,13 +1,13 @@ -import { roundRobinRandomImprove } from '../src/RoundRobinRandomImprove'; +import { AssetId, CslTestUtil, SelectionConstraints } from '@cardano-sdk/util-dev'; +import { InputSelectionError, InputSelectionFailure } from '../src/InputSelectionError'; import { - assertInputSelectionProperties, assertFailureProperties, + assertInputSelectionProperties, generateSelectionParams, testInputSelectionFailureMode, testInputSelectionProperties } from './util'; -import { InputSelectionError, InputSelectionFailure } from '../src/InputSelectionError'; -import { AssetId, CslTestUtil, SelectionConstraints } from '@cardano-sdk/util-dev'; +import { roundRobinRandomImprove } from '../src/RoundRobinRandomImprove'; import fc from 'fast-check'; describe('RoundRobinRandomImprove', () => { @@ -15,18 +15,18 @@ describe('RoundRobinRandomImprove', () => { describe('Properties', () => { it('No change', async () => { await testInputSelectionProperties({ - getAlgorithm: roundRobinRandomImprove, - createUtxo: () => [CslTestUtil.createUnspentTxOutput({ coins: 3_000_000n })], createOutputs: () => [CslTestUtil.createOutput({ coins: 3_000_000n })], + createUtxo: () => [CslTestUtil.createUnspentTxOutput({ coins: 3_000_000n })], + getAlgorithm: roundRobinRandomImprove, mockConstraints: SelectionConstraints.MOCK_NO_CONSTRAINTS }); }); it('No outputs', async () => { // Regression await testInputSelectionProperties({ - getAlgorithm: roundRobinRandomImprove, - createUtxo: () => [CslTestUtil.createUnspentTxOutput({ coins: 11_999_994n })], createOutputs: () => [], + createUtxo: () => [CslTestUtil.createUnspentTxOutput({ coins: 11_999_994n })], + getAlgorithm: roundRobinRandomImprove, mockConstraints: { ...SelectionConstraints.MOCK_NO_CONSTRAINTS, minimumCoinQuantity: 9_999_991n, @@ -39,108 +39,108 @@ describe('RoundRobinRandomImprove', () => { describe('UtxoBalanceInsufficient', () => { it('Coin (Outputs>UTxO)', async () => { await testInputSelectionFailureMode({ - getAlgorithm: roundRobinRandomImprove, - createUtxo: () => [ - CslTestUtil.createUnspentTxOutput({ coins: 3_000_000n }), - CslTestUtil.createUnspentTxOutput({ coins: 10_000_000n }) - ], createOutputs: () => [ CslTestUtil.createOutput({ coins: 12_000_000n }), CslTestUtil.createOutput({ coins: 2_000_000n }) ], - mockConstraints: SelectionConstraints.MOCK_NO_CONSTRAINTS, - expectedError: InputSelectionFailure.UtxoBalanceInsufficient + createUtxo: () => [ + CslTestUtil.createUnspentTxOutput({ coins: 3_000_000n }), + CslTestUtil.createUnspentTxOutput({ coins: 10_000_000n }) + ], + expectedError: InputSelectionFailure.UtxoBalanceInsufficient, + getAlgorithm: roundRobinRandomImprove, + mockConstraints: SelectionConstraints.MOCK_NO_CONSTRAINTS }); }); it('Coin (Outputs+Fee>UTxO)', async () => { await testInputSelectionFailureMode({ - getAlgorithm: roundRobinRandomImprove, + createOutputs: () => [CslTestUtil.createOutput({ coins: 9_000_000n })], createUtxo: () => [ CslTestUtil.createUnspentTxOutput({ coins: 4_000_000n }), CslTestUtil.createUnspentTxOutput({ coins: 5_000_000n }) ], - createOutputs: () => [CslTestUtil.createOutput({ coins: 9_000_000n })], + expectedError: InputSelectionFailure.UtxoBalanceInsufficient, + getAlgorithm: roundRobinRandomImprove, mockConstraints: { ...SelectionConstraints.MOCK_NO_CONSTRAINTS, minimumCost: 1n - }, - expectedError: InputSelectionFailure.UtxoBalanceInsufficient + } }); }); it('Asset', async () => { await testInputSelectionFailureMode({ - getAlgorithm: roundRobinRandomImprove, + createOutputs: () => [CslTestUtil.createOutput({ assets: { [AssetId.TSLA]: 7001n }, coins: 5_000_000n })], createUtxo: () => [ - CslTestUtil.createUnspentTxOutput({ coins: 10_000_000n, assets: { [AssetId.TSLA]: 7000n } }) + CslTestUtil.createUnspentTxOutput({ assets: { [AssetId.TSLA]: 7000n }, coins: 10_000_000n }) ], - createOutputs: () => [CslTestUtil.createOutput({ coins: 5_000_000n, assets: { [AssetId.TSLA]: 7001n } })], - mockConstraints: SelectionConstraints.MOCK_NO_CONSTRAINTS, - expectedError: InputSelectionFailure.UtxoBalanceInsufficient + expectedError: InputSelectionFailure.UtxoBalanceInsufficient, + getAlgorithm: roundRobinRandomImprove, + mockConstraints: SelectionConstraints.MOCK_NO_CONSTRAINTS }); }); it('No UTxO', async () => { await testInputSelectionFailureMode({ - getAlgorithm: roundRobinRandomImprove, - createUtxo: () => [], createOutputs: () => [CslTestUtil.createOutput({ coins: 5_000_000n })], - mockConstraints: SelectionConstraints.MOCK_NO_CONSTRAINTS, - expectedError: InputSelectionFailure.UtxoBalanceInsufficient + createUtxo: () => [], + expectedError: InputSelectionFailure.UtxoBalanceInsufficient, + getAlgorithm: roundRobinRandomImprove, + mockConstraints: SelectionConstraints.MOCK_NO_CONSTRAINTS }); }); }); describe('UTxO Fully Depleted', () => { it('Change bundle value is less than constrained', async () => { await testInputSelectionFailureMode({ - getAlgorithm: roundRobinRandomImprove, + createOutputs: () => [CslTestUtil.createOutput({ coins: 2_999_999n })], createUtxo: () => [ CslTestUtil.createUnspentTxOutput({ coins: 1_000_000n }), CslTestUtil.createUnspentTxOutput({ coins: 2_000_000n }) ], - createOutputs: () => [CslTestUtil.createOutput({ coins: 2_999_999n })], + expectedError: InputSelectionFailure.UtxoFullyDepleted, + getAlgorithm: roundRobinRandomImprove, mockConstraints: { ...SelectionConstraints.MOCK_NO_CONSTRAINTS, minimumCoinQuantity: 2n - }, - expectedError: InputSelectionFailure.UtxoFullyDepleted + } }); }); it('Change bundle size exceeds constraint', async () => { await testInputSelectionFailureMode({ - getAlgorithm: roundRobinRandomImprove, - createUtxo: () => [ - CslTestUtil.createUnspentTxOutput({ - coins: 2_000_000n, - assets: { [AssetId.TSLA]: 1000n, [AssetId.PXL]: 1000n } - }) - ], createOutputs: () => [ CslTestUtil.createOutput({ - coins: 1_000_000n, - assets: { [AssetId.TSLA]: 500n, [AssetId.PXL]: 500n } + assets: { [AssetId.TSLA]: 500n, [AssetId.PXL]: 500n }, + coins: 1_000_000n + }) + ], + createUtxo: () => [ + CslTestUtil.createUnspentTxOutput({ + assets: { [AssetId.TSLA]: 1000n, [AssetId.PXL]: 1000n }, + coins: 2_000_000n }) ], + expectedError: InputSelectionFailure.UtxoFullyDepleted, + getAlgorithm: roundRobinRandomImprove, mockConstraints: { ...SelectionConstraints.MOCK_NO_CONSTRAINTS, maxTokenBundleSize: 1 - }, - expectedError: InputSelectionFailure.UtxoFullyDepleted + } }); }); }); it('Maximum Input Count Exceeded', async () => { await testInputSelectionFailureMode({ - getAlgorithm: roundRobinRandomImprove, + createOutputs: () => [CslTestUtil.createOutput({ coins: 6_000_000n })], createUtxo: () => [ CslTestUtil.createUnspentTxOutput({ coins: 2_000_000n }), CslTestUtil.createUnspentTxOutput({ coins: 2_000_000n }), CslTestUtil.createUnspentTxOutput({ coins: 3_000_000n }) ], - createOutputs: () => [CslTestUtil.createOutput({ coins: 6_000_000n })], + expectedError: InputSelectionFailure.MaximumInputCountExceeded, + getAlgorithm: roundRobinRandomImprove, mockConstraints: { ...SelectionConstraints.MOCK_NO_CONSTRAINTS, selectionLimit: 2 - }, - expectedError: InputSelectionFailure.MaximumInputCountExceeded + } }); }); // "UTxO Not Fragmented Enough" doesn't apply for this algorithm @@ -161,15 +161,15 @@ describe('RoundRobinRandomImprove', () => { try { const results = await algorithm.select({ - utxo: new Set(utxo), - outputs, constraints: SelectionConstraints.mockConstraintsToConstraints(constraints), - implicitCoin + implicitCoin, + outputs, + utxo: new Set(utxo) }); - assertInputSelectionProperties({ results, outputs, utxo, constraints, implicitCoin }); + assertInputSelectionProperties({ constraints, implicitCoin, outputs, results, utxo }); } catch (error) { if (error instanceof InputSelectionError) { - assertFailureProperties({ error, utxoAmounts, outputsAmounts, constraints, implicitCoin }); + assertFailureProperties({ constraints, error, implicitCoin, outputsAmounts, utxoAmounts }); } else { throw error; } diff --git a/packages/cip2/test/selectionConstraints.test.ts b/packages/cip2/test/selectionConstraints.test.ts index 2b54748d400..f46915634f4 100644 --- a/packages/cip2/test/selectionConstraints.test.ts +++ b/packages/cip2/test/selectionConstraints.test.ts @@ -2,19 +2,19 @@ /* eslint-disable no-loop-func */ /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable unicorn/consistent-function-scoping */ -import { InvalidProtocolParametersError, CSL, coreToCsl } from '@cardano-sdk/core'; import { AssetId } from '@cardano-sdk/util-dev'; -import { defaultSelectionConstraints, DefaultSelectionConstraintsProps } from '../src/selectionConstraints'; +import { CSL, InvalidProtocolParametersError, coreToCsl } from '@cardano-sdk/core'; +import { DefaultSelectionConstraintsProps, defaultSelectionConstraints } from '../src/selectionConstraints'; import { ProtocolParametersForInputSelection, SelectionSkeleton } from '../src/types'; jest.mock('@emurgo/cardano-serialization-lib-nodejs', () => { const actualCsl = jest.requireActual('@emurgo/cardano-serialization-lib-nodejs'); return { ...actualCsl, - min_fee: jest.fn(), Value: { new: jest.fn() - } + }, + min_fee: jest.fn() }; }); const cslActual = jest.requireActual('@emurgo/cardano-serialization-lib-nodejs'); @@ -22,11 +22,11 @@ const cslMock = jest.requireMock('@emurgo/cardano-serialization-lib-nodejs'); describe('defaultSelectionConstraints', () => { const protocolParameters = { - minFeeCoefficient: 44, - minFeeConstant: 155_381, coinsPerUtxoWord: 34_482, maxTxSize: 16_384, - maxValueSize: 5000 + maxValueSize: 5000, + minFeeCoefficient: 44, + minFeeConstant: 155_381 } as ProtocolParametersForInputSelection; it('Invalid parameters', () => { @@ -46,8 +46,8 @@ describe('defaultSelectionConstraints', () => { const buildTx = jest.fn(); const selectionSkeleton = {} as SelectionSkeleton; const constraints = defaultSelectionConstraints({ - protocolParameters, - buildTx + buildTx, + protocolParameters }); const result = await constraints.computeMinimumCost(selectionSkeleton); expect(result).toEqual(fee); @@ -59,11 +59,11 @@ describe('defaultSelectionConstraints', () => { cslMock.Value.new.mockImplementation(cslActual.Value.new); const withAssets = coreToCsl .value({ - coins: 10_000n, assets: { [AssetId.TSLA]: 5000n, [AssetId.PXL]: 3000n - } + }, + coins: 10_000n }) .multiasset(); const constraints = defaultSelectionConstraints({ @@ -81,8 +81,8 @@ describe('defaultSelectionConstraints', () => { it("doesn't exceed max tx size", async () => { const constraints = defaultSelectionConstraints({ - protocolParameters, - buildTx: buildTxOfLength(protocolParameters.maxTxSize!) + buildTx: buildTxOfLength(protocolParameters.maxTxSize!), + protocolParameters }); expect(await constraints.computeSelectionLimit({ inputs: new Set([1, 2]) as any } as SelectionSkeleton)).toEqual( 2 @@ -91,8 +91,8 @@ describe('defaultSelectionConstraints', () => { it('exceeds max tx size', async () => { const constraints = defaultSelectionConstraints({ - protocolParameters, - buildTx: buildTxOfLength(protocolParameters.maxTxSize! + 1) + buildTx: buildTxOfLength(protocolParameters.maxTxSize! + 1), + protocolParameters }); expect(await constraints.computeSelectionLimit({ inputs: new Set([1, 2]) as any } as SelectionSkeleton)).toEqual( 3 @@ -110,8 +110,8 @@ describe('defaultSelectionConstraints', () => { it('empty bundle', () => { const constraints = defaultSelectionConstraints({ - protocolParameters, - buildTx: jest.fn() + buildTx: jest.fn(), + protocolParameters }); expect(constraints.tokenBundleSizeExceedsLimit()).toBe(false); }); diff --git a/packages/cip2/test/util/properties.ts b/packages/cip2/test/util/properties.ts index e13c7831af7..a5d59c8634c 100644 --- a/packages/cip2/test/util/properties.ts +++ b/packages/cip2/test/util/properties.ts @@ -1,7 +1,7 @@ import { AssetId, SelectionConstraints } from '@cardano-sdk/util-dev'; -import { SelectionResult } from '../../src/types'; -import { cslUtil, Cardano, CSL, cslToCore } from '@cardano-sdk/core'; +import { CSL, Cardano, cslToCore, cslUtil } from '@cardano-sdk/core'; import { InputSelectionError, InputSelectionFailure } from '../../src/InputSelectionError'; +import { SelectionResult } from '../../src/types'; import fc, { Arbitrary } from 'fast-check'; const assertExtraChangeProperties = ( @@ -54,7 +54,7 @@ const inputSelectionTotals = ({ const vChange = Cardano.util.coalesceValueQuantities( [...results.selection.change].map((value) => cslToCore.value(value)) ); - return { vSelected, vRequested, vChange }; + return { vChange, vRequested, vSelected }; }; export const assertInputSelectionProperties = ({ @@ -70,7 +70,7 @@ export const assertInputSelectionProperties = ({ constraints: SelectionConstraints.MockSelectionConstraints; implicitCoin?: Cardano.ImplicitCoin; }) => { - const { vSelected, vRequested, vChange } = inputSelectionTotals({ results, outputs, implicitCoin }); + const { vSelected, vRequested, vChange } = inputSelectionTotals({ implicitCoin, outputs, results }); // Coverage of Payments expect(vSelected.coins).toBeGreaterThanOrEqual(vRequested.coins); @@ -163,12 +163,11 @@ export const generateSelectionParams = (() => { fc .array( fc.record({ - coins: fc.bigUint(cslUtil.MAX_U64 - implicitCoin), assets: fc.oneof( fc .set(fc.oneof(...AssetId.All.map((asset) => fc.constant(asset)))) .chain((assets) => - fc.tuple(...assets.map((asset) => fc.bigUint(cslUtil.MAX_U64).map((amount) => ({ asset, amount })))) + fc.tuple(...assets.map((asset) => fc.bigUint(cslUtil.MAX_U64).map((amount) => ({ amount, asset })))) ) .map((assets) => assets.reduce((quantities, { amount, asset }) => { @@ -177,7 +176,8 @@ export const generateSelectionParams = (() => { }, {} as Cardano.TokenMap) ), fc.constant(void 0) - ) + ), + coins: fc.bigUint(cslUtil.MAX_U64 - implicitCoin) }), { maxLength: 11 } ) @@ -223,15 +223,15 @@ export const generateSelectionParams = (() => { }> => generateImplicitCoin.chain((implicitCoin) => fc.record({ - utxoAmounts: arrayOfCoinAndAssets(implicitCoin?.input), - outputsAmounts: arrayOfCoinAndAssets(implicitCoin?.deposit), constraints: fc.record({ maxTokenBundleSize: fc.nat(AssetId.All.length), minimumCoinQuantity: fc.oneof(...[0n, 1n, 34_482n * 29n, 9_999_991n].map((n) => fc.constant(n))), minimumCost: fc.oneof(...[0n, 1n, 200_000n, 2_000_003n].map((n) => fc.constant(n))), selectionLimit: fc.oneof(...[0, 1, 2, 7, 30, Number.MAX_SAFE_INTEGER].map((n) => fc.constant(n))) }), - implicitCoin: fc.constant(implicitCoin) + implicitCoin: fc.constant(implicitCoin), + outputsAmounts: arrayOfCoinAndAssets(implicitCoin?.deposit), + utxoAmounts: arrayOfCoinAndAssets(implicitCoin?.input) }) ); })(); diff --git a/packages/cip2/test/util/tests.ts b/packages/cip2/test/util/tests.ts index 592dd6aceb9..0335af27d6a 100644 --- a/packages/cip2/test/util/tests.ts +++ b/packages/cip2/test/util/tests.ts @@ -1,6 +1,6 @@ import { CSL } from '@cardano-sdk/core'; -import { InputSelector } from '../../src/types'; import { InputSelectionError, InputSelectionFailure } from '../../src/InputSelectionError'; +import { InputSelector } from '../../src/types'; import { SelectionConstraints } from '@cardano-sdk/util-dev'; import { assertInputSelectionProperties } from './properties'; @@ -44,7 +44,7 @@ export const testInputSelectionFailureMode = async ({ const outputs = new Set(createOutputs()); const algorithm = getAlgorithm(); await expect( - algorithm.select({ utxo, outputs, constraints: SelectionConstraints.mockConstraintsToConstraints(mockConstraints) }) + algorithm.select({ constraints: SelectionConstraints.mockConstraintsToConstraints(mockConstraints), outputs, utxo }) ).rejects.toThrowError(new InputSelectionError(expectedError)); }; @@ -61,9 +61,9 @@ export const testInputSelectionProperties = async ({ const outputs = new Set(createOutputs()); const algorithm = getAlgorithm(); const results = await algorithm.select({ - utxo, + constraints: SelectionConstraints.mockConstraintsToConstraints(mockConstraints), outputs, - constraints: SelectionConstraints.mockConstraintsToConstraints(mockConstraints) + utxo }); - assertInputSelectionProperties({ results, outputs, constraints: mockConstraints, utxo }); + assertInputSelectionProperties({ constraints: mockConstraints, outputs, results, utxo }); }; diff --git a/packages/cip30/package.json b/packages/cip30/package.json index 5e6ea13afff..b5dcc76a954 100644 --- a/packages/cip30/package.json +++ b/packages/cip30/package.json @@ -17,6 +17,7 @@ "tscNoEmit": "shx echo typescript --noEmit command not implemented yet", "cleanup": "shx rm -rf dist node_modules", "lint": "eslint --ignore-path ../../.eslintignore \"**/*.ts\"", + "lint:fix": "eslint --fix --ignore-path ../../.eslintignore \"**/*.ts\"", "test": "jest -c ./jest.config.js", "coverage": "shx echo No coverage report for this package", "prepack": "yarn build", diff --git a/packages/cip30/src/BrowserExtension/handleMessages.ts b/packages/cip30/src/BrowserExtension/handleMessages.ts index fc72c5bbdb3..ab56e701b35 100644 --- a/packages/cip30/src/BrowserExtension/handleMessages.ts +++ b/packages/cip30/src/BrowserExtension/handleMessages.ts @@ -1,7 +1,7 @@ -import { dummyLogger, Logger } from 'ts-log'; -import browser from 'webextension-polyfill'; +import { Logger, dummyLogger } from 'ts-log'; import { Message } from './types'; import { WalletApi } from '../Wallet'; +import browser from 'webextension-polyfill'; export const handleMessages = (walletApi: WalletApi, logger: Logger = dummyLogger): void => { browser.runtime.onMessage.addListener(async (msg: Message) => { diff --git a/packages/cip30/src/BrowserExtension/sendMessage.ts b/packages/cip30/src/BrowserExtension/sendMessage.ts index eb4c500c494..22ff3d1d4aa 100644 --- a/packages/cip30/src/BrowserExtension/sendMessage.ts +++ b/packages/cip30/src/BrowserExtension/sendMessage.ts @@ -1,7 +1,7 @@ -import browser from 'webextension-polyfill'; -import { dummyLogger, Logger } from 'ts-log'; +import { Logger, dummyLogger } from 'ts-log'; import { Message } from './types'; import { WalletApi } from '../Wallet'; +import browser from 'webextension-polyfill'; export const sendMessage = (msg: Message, logger: Logger = dummyLogger): Promise => { logger.debug('sendMessage', msg); diff --git a/packages/cip30/src/BrowserExtension/uiWallet.ts b/packages/cip30/src/BrowserExtension/uiWallet.ts index e2a31caa664..d295067a1bb 100644 --- a/packages/cip30/src/BrowserExtension/uiWallet.ts +++ b/packages/cip30/src/BrowserExtension/uiWallet.ts @@ -1,7 +1,7 @@ +import { Logger, dummyLogger } from 'ts-log'; +import { Message } from './types'; import { WalletApi } from '..'; -import { dummyLogger, Logger } from 'ts-log'; import { sendMessage } from './sendMessage'; -import { Message } from './types'; export const createUiWallet = (logger: Logger = dummyLogger): WalletApi => { const methodNames = [ @@ -20,7 +20,7 @@ export const createUiWallet = (logger: Logger = dummyLogger): WalletApi => { Object.fromEntries( methodNames.map((method) => [ method, - (...args: Message['arguments']) => sendMessage({ method, arguments: args }, logger) + (...args: Message['arguments']) => sendMessage({ arguments: args, method }, logger) ]) ) )) diff --git a/packages/cip30/src/Wallet/Wallet.ts b/packages/cip30/src/Wallet/Wallet.ts index e2a29b8228f..7910dddd078 100644 --- a/packages/cip30/src/Wallet/Wallet.ts +++ b/packages/cip30/src/Wallet/Wallet.ts @@ -1,6 +1,6 @@ +import { APIErrorCode, ApiError } from '../errors'; +import { Logger, dummyLogger } from 'ts-log'; import { WalletApi } from './types'; -import { ApiError, APIErrorCode } from '../errors'; -import { dummyLogger, Logger } from 'ts-log'; import { WindowMaybeWithCardano } from '../injectWindow'; /** @@ -57,10 +57,10 @@ export class Wallet { public getPublicApi(window: WindowMaybeWithCardano) { return { - name: this.name, - version: this.version, enable: this.enable.bind(this, window), - isEnabled: this.isEnabled.bind(this, window) + isEnabled: this.isEnabled.bind(this, window), + name: this.name, + version: this.version }; } @@ -78,9 +78,9 @@ export class Wallet { this.options.storage?.setItem(this.name, JSON.stringify([...currentList, appName])); this.logger.debug( { + allowList: this.getAllowList(), module: 'Wallet', - walletName: this.name, - allowList: this.getAllowList() + walletName: this.name }, 'Allow list persisted' ); diff --git a/packages/cip30/src/Wallet/types.ts b/packages/cip30/src/Wallet/types.ts index 22ca373a6c7..83dc43ae508 100644 --- a/packages/cip30/src/Wallet/types.ts +++ b/packages/cip30/src/Wallet/types.ts @@ -1,5 +1,5 @@ -import { Cardano } from '@cardano-sdk/core'; import { Bytes, Cbor, Paginate } from '../types'; +import { Cardano } from '@cardano-sdk/core'; /** * If `amount` is `undefined`, this shall return a list of all UTxOs (unspent transaction outputs) diff --git a/packages/cip30/src/injectWindow.ts b/packages/cip30/src/injectWindow.ts index 6c2a9aaae8a..d941994fcac 100644 --- a/packages/cip30/src/injectWindow.ts +++ b/packages/cip30/src/injectWindow.ts @@ -1,5 +1,5 @@ +import { Logger, dummyLogger } from 'ts-log'; import { Wallet, WalletPublic } from './Wallet'; -import { dummyLogger, Logger } from 'ts-log'; export type WindowMaybeWithCardano = Window & { cardano?: { [k: string]: WalletPublic } }; diff --git a/packages/cip30/test/Wallet.test.ts b/packages/cip30/test/Wallet.test.ts index d9d3acb5e8f..7871019bfa3 100644 --- a/packages/cip30/test/Wallet.test.ts +++ b/packages/cip30/test/Wallet.test.ts @@ -1,9 +1,9 @@ /* eslint-disable sonarjs/no-duplicate-string */ /* eslint-disable @typescript-eslint/no-unused-vars */ +import * as testWallet from './testWallet'; import { Wallet, WalletApi, WalletOptions } from '../src/Wallet'; import { mocks } from 'mock-browser'; -import * as testWallet from './testWallet'; const window = mocks.MockBrowser.createWindow(); // todo test persistAllowList: true when design is finalised @@ -15,14 +15,14 @@ if (process.env.DEBUG) { describe('Wallet', () => { const apiMethods = [ - 'getUtxos', 'getBalance', - 'getUsedAddresses', - 'getUnusedAddresses', 'getChangeAddress', 'getRewardAddresses', - 'signTx', + 'getUnusedAddresses', + 'getUsedAddresses', + 'getUtxos', 'signData', + 'signTx', 'submitTx' ]; let wallet: Wallet; @@ -73,8 +73,8 @@ describe('Wallet', () => { const uxtos = await api.getUtxos(); expect(uxtos).toEqual([ [ - { txId: '123456', index: 0 }, - { address: 'asdf', value: { coins: 100n, assets: {} } } + { index: 0, txId: '123456' }, + { address: 'asdf', value: { assets: {}, coins: 100n } } ] ]); }); diff --git a/packages/cip30/test/injectWindow.test.ts b/packages/cip30/test/injectWindow.test.ts index 02fa23b039c..57b5cc4490b 100644 --- a/packages/cip30/test/injectWindow.test.ts +++ b/packages/cip30/test/injectWindow.test.ts @@ -1,7 +1,7 @@ -import { mocks } from 'mock-browser'; import { Wallet } from '../src/Wallet'; +import { WindowMaybeWithCardano, injectWindow } from '../src/injectWindow'; import { api, properties, requestAccess } from './testWallet'; -import { injectWindow, WindowMaybeWithCardano } from '../src/injectWindow'; +import { mocks } from 'mock-browser'; describe('injectWindow', () => { let wallet: Wallet; @@ -27,7 +27,7 @@ describe('injectWindow', () => { let anotherObj: any; beforeEach(() => { - anotherObj = { could: 'be', anything: 'here' }; + anotherObj = { anything: 'here', could: 'be' }; expect(window.cardano).not.toBeDefined(); window.cardano = {} as WindowMaybeWithCardano; window.cardano['another-obj'] = anotherObj; @@ -38,7 +38,7 @@ describe('injectWindow', () => { expect(window.cardano).toBeDefined(); injectWindow(window, wallet); expect(window.cardano[properties.name].name).toBe(properties.name); - expect(Object.keys(window.cardano[properties.name])).toEqual(['name', 'version', 'enable', 'isEnabled']); + expect(Object.keys(window.cardano[properties.name])).toEqual(['enable', 'isEnabled', 'name', 'version']); expect(window.cardano['another-obj']).toBe(anotherObj); }); }); diff --git a/packages/cip30/test/testWallet.ts b/packages/cip30/test/testWallet.ts index 015eb406dce..eb53c5a9e74 100644 --- a/packages/cip30/test/testWallet.ts +++ b/packages/cip30/test/testWallet.ts @@ -1,22 +1,22 @@ import { RequestAccess, WalletApi } from '../src/Wallet'; export const api = { + getBalance: async () => '100', + getChangeAddress: async () => 'change-address', + getRewardAddresses: async () => ['reward-address-1', 'reward-address-2'], + getUnusedAddresses: async () => ['unused-address-1', 'unused-address-2', 'unused-address-3'], + getUsedAddresses: async () => ['used-address-1', 'used-address-2', 'used-address-3'], getUtxos: async (_amount) => [ [ { - txId: '123456', - index: 0 + index: 0, + txId: '123456' }, - { address: 'asdf', value: { coins: 100n, assets: {} } } + { address: 'asdf', value: { assets: {}, coins: 100n } } ] ], - getBalance: async () => '100', - getUsedAddresses: async () => ['used-address-1', 'used-address-2', 'used-address-3'], - getUnusedAddresses: async () => ['unused-address-1', 'unused-address-2', 'unused-address-3'], - getChangeAddress: async () => 'change-address', - getRewardAddresses: async () => ['reward-address-1', 'reward-address-2'], - signTx: async (_tx) => 'signedTransaction', signData: async (_addr, _sig) => 'signedData', + signTx: async (_tx) => 'signedTransaction', submitTx: async (_tx) => 'transactionId' }; diff --git a/packages/core/package.json b/packages/core/package.json index 4a7a4a075ac..94c92a96be5 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -14,6 +14,7 @@ "tscNoEmit": "shx echo typescript --noEmit command not implemented yet", "cleanup": "shx rm -rf dist node_modules", "lint": "eslint --ignore-path ../../.eslintignore \"**/*.ts\"", + "lint:fix": "eslint --fix --ignore-path ../../.eslintignore \"**/*.ts\"", "test": "jest -c ./jest.config.js", "coverage": "shx echo No coverage report for this package", "prepack": "yarn build" diff --git a/packages/core/src/Asset/util.ts b/packages/core/src/Asset/util.ts index e0f92115b7a..352f21c55ef 100644 --- a/packages/core/src/Asset/util.ts +++ b/packages/core/src/Asset/util.ts @@ -1,5 +1,5 @@ -import { TokenMap } from '../Cardano'; import { CSL } from '../CSL'; +import { TokenMap } from '../Cardano'; export type AssetId = string; @@ -16,8 +16,8 @@ export const parseAssetId = (assetId: AssetId) => { const policyId = policyIdFromAssetId(assetId); const assetName = assetNameFromAssetId(assetId); return { - scriptHash: CSL.ScriptHash.from_bytes(Buffer.from(policyId, 'hex')), - assetName: CSL.AssetName.new(Buffer.from(assetName, 'hex')) + assetName: CSL.AssetName.new(Buffer.from(assetName, 'hex')), + scriptHash: CSL.ScriptHash.from_bytes(Buffer.from(policyId, 'hex')) }; }; diff --git a/packages/core/src/CSL/coreToCsl.ts b/packages/core/src/CSL/coreToCsl.ts index 89e0660899d..9fe5bd617b6 100644 --- a/packages/core/src/CSL/coreToCsl.ts +++ b/packages/core/src/CSL/coreToCsl.ts @@ -1,3 +1,5 @@ +import * as Asset from '../Asset'; +import * as Cardano from '../Cardano'; import { Address, Assets, @@ -9,8 +11,6 @@ import { TransactionUnspentOutput, Value } from '@emurgo/cardano-serialization-lib-nodejs'; -import * as Asset from '../Asset'; -import * as Cardano from '../Cardano'; export const value = ({ coins, assets }: Cardano.Value): Value => { const result = Value.new(BigNum.from_str(coins.toString())); diff --git a/packages/core/src/CSL/cslToCore.ts b/packages/core/src/CSL/cslToCore.ts index 95af1c2d3e6..4c892a8c372 100644 --- a/packages/core/src/CSL/cslToCore.ts +++ b/packages/core/src/CSL/cslToCore.ts @@ -1,5 +1,5 @@ -import { CSL } from '.'; import { Asset, Cardano } from '..'; +import { CSL } from '.'; import { Transaction } from '@emurgo/cardano-serialization-lib-nodejs'; export const tx = (_input: Transaction): Cardano.TxAlonzo => { @@ -32,7 +32,7 @@ export const value = (cslValue: CSL.Value): Cardano.Value => { }; export const txIn = (input: CSL.TransactionInput, address: Cardano.Address): Cardano.TxIn => ({ - txId: Buffer.from(input.transaction_id().to_bytes()).toString('hex'), + address, index: input.index(), - address + txId: Buffer.from(input.transaction_id().to_bytes()).toString('hex') }); diff --git a/packages/core/src/Cardano/types/DelegationsAndRewards.ts b/packages/core/src/Cardano/types/DelegationsAndRewards.ts index bc78b6c8b64..f0b6d43d555 100644 --- a/packages/core/src/Cardano/types/DelegationsAndRewards.ts +++ b/packages/core/src/Cardano/types/DelegationsAndRewards.ts @@ -1,4 +1,4 @@ -import { PoolId, Lovelace } from '.'; +import { Lovelace, PoolId } from '.'; /** * TODO: re-export Ogmios/DelegationsAndRewards type after it changes lovelaces to bigint; diff --git a/packages/core/src/Cardano/types/StakePool.ts b/packages/core/src/Cardano/types/StakePool.ts index c9c9589caa1..2b21619feba 100644 --- a/packages/core/src/Cardano/types/StakePool.ts +++ b/packages/core/src/Cardano/types/StakePool.ts @@ -1,6 +1,6 @@ -import { PoolParameters } from '@cardano-ogmios/schema'; -import { Hash16, Lovelace, PoolMetadata } from '.'; import { ExtendedStakePoolMetadata } from './ExtendedStakePoolMetadata'; +import { Hash16, Lovelace, PoolMetadata } from '.'; +import { PoolParameters } from '@cardano-ogmios/schema'; /** * Within range [0; 1] diff --git a/packages/core/src/Cardano/types/Utxo.ts b/packages/core/src/Cardano/types/Utxo.ts index aeb18495ec8..645cb167027 100644 --- a/packages/core/src/Cardano/types/Utxo.ts +++ b/packages/core/src/Cardano/types/Utxo.ts @@ -1,4 +1,4 @@ -import { Hash16, Address } from '.'; +import { Address, Hash16 } from '.'; import { TxIn as OgmiosTxIn } from '@cardano-ogmios/schema'; import { Value } from './Value'; diff --git a/packages/core/src/Cardano/util.ts b/packages/core/src/Cardano/util.ts index 18f5f8e997f..9032375a476 100644 --- a/packages/core/src/Cardano/util.ts +++ b/packages/core/src/Cardano/util.ts @@ -10,6 +10,6 @@ export const computeMinUtxoValue = (coinsPerUtxoWord: bigint): bigint => coinsPe * Sum all quantities */ export const coalesceValueQuantities = (quantities: Value[]): Value => ({ - coins: BigIntMath.sum(quantities.map(({ coins }) => coins)), - assets: Asset.util.coalesceTokenMaps(quantities.map(({ assets }) => assets)) + assets: Asset.util.coalesceTokenMaps(quantities.map(({ assets }) => assets)), + coins: BigIntMath.sum(quantities.map(({ coins }) => coins)) }); diff --git a/packages/core/test/Address/util.test.ts b/packages/core/test/Address/util.test.ts index b1ffea6e5fc..c693224f699 100644 --- a/packages/core/test/Address/util.test.ts +++ b/packages/core/test/Address/util.test.ts @@ -1,11 +1,7 @@ +/* eslint-disable max-len */ import { isAddress } from '../../src/Address/util'; export const addresses = { - shelley: { - testnet: - 'addr_test1qqydn46r6mhge0kfpqmt36m6q43knzsd9ga32n96m89px3nuzcjqw982pcftgx53fu5527z2cj2tkx2h8ux2vxsg475qypp3m9', - mainnet: 'addr1qx52knza2h5x090n4a5r7yraz3pwcamk9ppvuh7e26nfks7pnmhxqavtqy02zezklh27jt9r6z62sav3mugappdc7xnskxy2pn' - }, byron: { mainnet: { daedalus: @@ -19,9 +15,14 @@ export const addresses = { } }, invalid: { - short: 'EkxDbkPo', networkMagic: - '3reY92cShRkjtmz7q31547czPNHbrhbRGhVLehTrNDNDNeDaKJwcM8aMmWg2zd7cHVFvhdui4a86nEdsSEE7g7kcZKKvBw7nzixnbX1' + '3reY92cShRkjtmz7q31547czPNHbrhbRGhVLehTrNDNDNeDaKJwcM8aMmWg2zd7cHVFvhdui4a86nEdsSEE7g7kcZKKvBw7nzixnbX1', + short: 'EkxDbkPo' + }, + shelley: { + mainnet: 'addr1qx52knza2h5x090n4a5r7yraz3pwcamk9ppvuh7e26nfks7pnmhxqavtqy02zezklh27jt9r6z62sav3mugappdc7xnskxy2pn', + testnet: + 'addr_test1qqydn46r6mhge0kfpqmt36m6q43knzsd9ga32n96m89px3nuzcjqw982pcftgx53fu5527z2cj2tkx2h8ux2vxsg475qypp3m9' } }; diff --git a/packages/core/test/CSL/coreToCsl.test.ts b/packages/core/test/CSL/coreToCsl.test.ts index 989da5fd918..8cd0cd5a2ad 100644 --- a/packages/core/test/CSL/coreToCsl.test.ts +++ b/packages/core/test/CSL/coreToCsl.test.ts @@ -1,20 +1,20 @@ import { Asset, CSL, Cardano, coreToCsl } from '../../src'; const txIn: Cardano.TxIn = { - txId: '0f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5', - index: 0, address: - 'addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3jcu5d8ps7zex2k2xt3uqxgjqnnj83ws8lhrn648jjxtwq2ytjqp' + 'addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3jcu5d8ps7zex2k2xt3uqxgjqnnj83ws8lhrn648jjxtwq2ytjqp', + index: 0, + txId: '0f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5' }; const txOut: Cardano.TxOut = { address: 'addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3jcu5d8ps7zex2k2xt3uqxgjqnnj83ws8lhrn648jjxtwq2ytjqp', value: { - coins: 10n, assets: { '2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740': 20n, '659f2917fb63f12b33667463ee575eeac1845bbc736b9c0bbc40ba8254534c41': 50n - } + }, + coins: 10n } }; diff --git a/packages/core/test/CSL/cslToCore.test.ts b/packages/core/test/CSL/cslToCore.test.ts index d06332b880e..bbcc4e09cbe 100644 --- a/packages/core/test/CSL/cslToCore.test.ts +++ b/packages/core/test/CSL/cslToCore.test.ts @@ -1,5 +1,5 @@ import { AssetId, CslTestUtil } from '@cardano-sdk/util-dev'; -import { cslToCore, coreToCsl, CSL } from '../../src'; +import { CSL, coreToCsl, cslToCore } from '../../src'; describe('cslToCore', () => { describe('value', () => { @@ -13,7 +13,7 @@ describe('cslToCore', () => { it('coin with assets', () => { const coins = 100_000n; const assets = { [AssetId.TSLA]: 100n, [AssetId.PXL]: 200n }; - const value = coreToCsl.value({ coins, assets }); + const value = coreToCsl.value({ assets, coins }); const quantities = cslToCore.value(value); expect(quantities.coins).toEqual(coins); expect(quantities.assets).toEqual(assets); diff --git a/packages/core/test/Cardano/util.test.ts b/packages/core/test/Cardano/util.test.ts index 37977feb1bd..93edbf3f728 100644 --- a/packages/core/test/Cardano/util.test.ts +++ b/packages/core/test/Cardano/util.test.ts @@ -14,25 +14,25 @@ describe('Cardano', () => { const TSLA_Asset = 'b32_1vk0jj9lmv0cjkvmxw337u467atqcgkauwd4eczaugzagyghp25lTSLA'; const PXL_Asset = 'b32_1rmy9mnhz0ukepmqlng0yee62ve7un05trpzxxg3lnjtqzp4dmmrPXL'; const q1: Cardano.Value = { - coins: 50n, assets: { - [TSLA_Asset]: 50n, - [PXL_Asset]: 100n - } + [PXL_Asset]: 100n, + [TSLA_Asset]: 50n + }, + coins: 50n }; const q2: Cardano.Value = { coins: 100n }; const q3: Cardano.Value = { - coins: 20n, assets: { [TSLA_Asset]: 20n - } + }, + coins: 20n }; expect(Cardano.util.coalesceValueQuantities([q1, q2, q3])).toEqual({ - coins: 170n, assets: { - [TSLA_Asset]: 70n, - [PXL_Asset]: 100n - } + [PXL_Asset]: 100n, + [TSLA_Asset]: 70n + }, + coins: 170n }); }); }); diff --git a/packages/golden-test-generator/package.json b/packages/golden-test-generator/package.json index ea91acb7cbc..a95670025cc 100644 --- a/packages/golden-test-generator/package.json +++ b/packages/golden-test-generator/package.json @@ -16,6 +16,7 @@ "cleanup": "shx rm -rf dist node_modules", "dev": "API_PORT=3000 OGMIOS_HOST=localhost OGMIOS_PORT=1337 ts-node-dev ./src/index.ts", "lint": "shx echo linting disabled in this package temporarily", + "lint:fix": "shx echo linting disabled in this package temporarily", "prepkg": "yarn build", "pkg": "yarn build && pkg -o build/golden-test-generator .", "prestart": "yarn build", diff --git a/packages/golden-test-generator/src/AddressBalance/getOnChainAddressBalances.ts b/packages/golden-test-generator/src/AddressBalance/getOnChainAddressBalances.ts index 87f81445efb..b51714c5a2e 100644 --- a/packages/golden-test-generator/src/AddressBalance/getOnChainAddressBalances.ts +++ b/packages/golden-test-generator/src/AddressBalance/getOnChainAddressBalances.ts @@ -35,7 +35,7 @@ export const getOnChainAddressBalances = ( ): Promise => { const logger = options?.logger ?? dummyLogger; const trackedAddressBalances: AddressBalances = Object.fromEntries( - addresses.map((address) => [address, { coins: 0, assets: {} }]) + addresses.map((address) => [address, { assets: {}, coins: 0 }]) ); const trackedTxs: ({ id: Schema.Hash16 } & Schema.Tx)[] = []; // eslint-disable-next-line sonarjs/cognitive-complexity @@ -45,6 +45,7 @@ export const getOnChainAddressBalances = ( // condition is met let draining = false; const response: AddressBalancesResponse = { + balances: {}, metadata: { cardano: { compactGenesis: await StateQuery.genesisConfig( @@ -52,8 +53,7 @@ export const getOnChainAddressBalances = ( ), intersection: undefined as unknown as ChainSync.Intersection } - }, - balances: {} + } }; try { const syncClient = await createChainSyncClient( diff --git a/packages/golden-test-generator/src/Block/getBlocks.ts b/packages/golden-test-generator/src/Block/getBlocks.ts index f13f43d1da1..ab7c0e85474 100644 --- a/packages/golden-test-generator/src/Block/getBlocks.ts +++ b/packages/golden-test-generator/src/Block/getBlocks.ts @@ -35,6 +35,7 @@ export const getBlocks = async ( // Required to ensure existing messages in the pipe are not processed after the completion condition is met let draining = false; const response: GetBlocksResponse = { + blocks: {}, metadata: { cardano: { compactGenesis: await StateQuery.genesisConfig( @@ -42,8 +43,7 @@ export const getBlocks = async ( ), intersection: undefined as unknown as ChainSync.Intersection } - }, - blocks: {} + } }; try { const syncClient = await createChainSyncClient( diff --git a/packages/golden-test-generator/src/Content.ts b/packages/golden-test-generator/src/Content.ts index f29df86425a..7391cdfec81 100644 --- a/packages/golden-test-generator/src/Content.ts +++ b/packages/golden-test-generator/src/Content.ts @@ -8,7 +8,7 @@ export type Metadata = { compactGenesis: Cardano.CompactGenesis; intersection: ChainSync.Intersection; }; - software: { + software: { name: string; version: string; commit: Pick; @@ -26,18 +26,18 @@ export const prepareContent = async ( }> => { const lastCommit = await getLastCommitPromise(); return { + body, metadata: { ...metadata, software: { - name: packageJson.name, - version: packageJson.version, commit: { hash: lastCommit.hash, tags: lastCommit.tags - } + }, + name: packageJson.name, + version: packageJson.version } - }, - body + } }; }; diff --git a/packages/golden-test-generator/src/index.ts b/packages/golden-test-generator/src/index.ts index b4ffd86a7a4..ce61918894b 100644 --- a/packages/golden-test-generator/src/index.ts +++ b/packages/golden-test-generator/src/index.ts @@ -19,11 +19,11 @@ console.log(chalk.blue('Cardano Golden Test Generator')); const createProgressBar = (lastblockHeight: number) => new SingleBar({ + barCompleteChar: '\u2588', + barIncompleteChar: '\u2591', format: `Syncing from genesis to block ${lastblockHeight} | ${chalk.blue( '{bar}' )} | {percentage}% || {value}/{total} Blocks`, - barCompleteChar: '\u2588', - barIncompleteChar: '\u2591', hideCursor: true, renderThrottle: 300 } as Options); diff --git a/packages/util-dev/package.json b/packages/util-dev/package.json index 5b7b18510fd..38f06b0ce0c 100644 --- a/packages/util-dev/package.json +++ b/packages/util-dev/package.json @@ -14,6 +14,7 @@ "tscNoEmit": "shx echo typescript --noEmit command not implemented yet", "cleanup": "shx rm -rf dist node_modules", "lint": "eslint --ignore-path ../../.eslintignore \"**/*.ts\"", + "lint:fix": "eslint --fix --ignore-path ../../.eslintignore \"**/*.ts\"", "test": "jest -c ./jest.config.js", "coverage": "yarn test --coverage", "prepack": "yarn build", diff --git a/packages/util-dev/src/createStubStakePoolSearchProvider.ts b/packages/util-dev/src/createStubStakePoolSearchProvider.ts index 615a0a19410..8f287d47346 100644 --- a/packages/util-dev/src/createStubStakePoolSearchProvider.ts +++ b/packages/util-dev/src/createStubStakePoolSearchProvider.ts @@ -1,26 +1,26 @@ -import { StakePoolSearchProvider } from '@cardano-sdk/core'; import { StakePool } from '@cardano-sdk/core/src/Cardano'; +import { StakePoolSearchProvider } from '@cardano-sdk/core'; import delay from 'delay'; export const somePartialStakePools: StakePool[] = [ { - id: 'pool1euf2nh92ehqfw7rpd4s9qgq34z8dg4pvfqhjmhggmzk95gcd402', hexId: 'cf12a9dcaacdc09778616d60502011a88ed4542c482f2ddd08d8ac5a', + id: 'pool1euf2nh92ehqfw7rpd4s9qgq34z8dg4pvfqhjmhggmzk95gcd402', metadata: { - name: 'Keiths PiTest', description: 'Keiths Pi test pool', - ticker: 'KPIT', - homepage: '' + homepage: '', + name: 'Keiths PiTest', + ticker: 'KPIT' } }, { - id: 'pool1fghrkl620rl3g54ezv56weeuwlyce2tdannm2hphs62syf3vyyh', hexId: '4a2e3b7f4a78ff1452b91329a7673c77c98ca96dece7b55c37869502', + id: 'pool1fghrkl620rl3g54ezv56weeuwlyce2tdannm2hphs62syf3vyyh', metadata: { - name: 'VEGASPool', description: 'VEGAS TestNet(2) ADA Pool', - ticker: 'VEGA2', - homepage: 'https://www.ada.vegas' + homepage: 'https://www.ada.vegas', + name: 'VEGASPool', + ticker: 'VEGA2' } } ] as StakePool[]; diff --git a/packages/util-dev/src/cslTestUtil.ts b/packages/util-dev/src/cslTestUtil.ts index e2edfd46a0f..4947756462a 100644 --- a/packages/util-dev/src/cslTestUtil.ts +++ b/packages/util-dev/src/cslTestUtil.ts @@ -1,4 +1,4 @@ -import { Cardano, CSL, coreToCsl } from '@cardano-sdk/core'; +import { CSL, Cardano, coreToCsl } from '@cardano-sdk/core'; export const createTxInput = (() => { let defaultIdx = 0; diff --git a/packages/util-dev/src/selectionConstraints.ts b/packages/util-dev/src/selectionConstraints.ts index 3b633ea1239..f68a801894c 100644 --- a/packages/util-dev/src/selectionConstraints.ts +++ b/packages/util-dev/src/selectionConstraints.ts @@ -9,8 +9,8 @@ export interface MockSelectionConstraints { } export const MOCK_NO_CONSTRAINTS: MockSelectionConstraints = { - minimumCoinQuantity: 0n, maxTokenBundleSize: Number.POSITIVE_INFINITY, + minimumCoinQuantity: 0n, minimumCost: 0n, selectionLimit: Number.POSITIVE_INFINITY }; diff --git a/packages/util-dev/test/cslTestUtil.test.ts b/packages/util-dev/test/cslTestUtil.test.ts index 90c34567245..46ca3ef8ad5 100644 --- a/packages/util-dev/test/cslTestUtil.test.ts +++ b/packages/util-dev/test/cslTestUtil.test.ts @@ -1,5 +1,5 @@ import { CSL } from '@cardano-sdk/core'; -import { createTxInput, createOutput, createUnspentTxOutput } from '../src/cslTestUtil'; +import { createOutput, createTxInput, createUnspentTxOutput } from '../src/cslTestUtil'; describe('cslUtil', () => { describe('createTxInput', () => { diff --git a/packages/wallet/package.json b/packages/wallet/package.json index 956885515c2..f8332852a26 100644 --- a/packages/wallet/package.json +++ b/packages/wallet/package.json @@ -19,7 +19,8 @@ "cleanup": "shx rm -rf dist node_modules", "coverage": "yarn test --coverage", "lint": "eslint --ignore-path ../../.eslintignore \"**/*.ts\"", - "prepack": "yarn build", + "lint:fix": "eslint --fix --ignore-path ../../.eslintignore \"**/*.ts\"", + "prepack": "yarn build", "test": "jest -c ./jest.config.js", "test:debug": "DEBUG=true yarn test" }, diff --git a/packages/wallet/src/BalanceTracker.ts b/packages/wallet/src/BalanceTracker.ts index 4e8d55dd2d0..f5cf750e5ed 100644 --- a/packages/wallet/src/BalanceTracker.ts +++ b/packages/wallet/src/BalanceTracker.ts @@ -1,7 +1,7 @@ import { Cardano } from '@cardano-sdk/core'; -import Emittery from 'emittery'; -import { dummyLogger } from 'ts-log'; import { UtxoRepository, UtxoRepositoryEvent, UtxoRepositoryFields } from './types'; +import { dummyLogger } from 'ts-log'; +import Emittery from 'emittery'; export interface Balance extends Cardano.Value { rewards: Cardano.Lovelace; diff --git a/packages/wallet/src/InMemoryTransactionTracker.ts b/packages/wallet/src/InMemoryTransactionTracker.ts index 85277cb928f..570eb072c91 100644 --- a/packages/wallet/src/InMemoryTransactionTracker.ts +++ b/packages/wallet/src/InMemoryTransactionTracker.ts @@ -1,10 +1,10 @@ +import { CSL, Cardano, ProviderError, ProviderFailure, WalletProvider } from '@cardano-sdk/core'; +import { Logger, dummyLogger } from 'ts-log'; +import { TransactionError, TransactionFailure } from './TransactionError'; import { TransactionTracker, TransactionTrackerEvents } from './types'; +import { TransactionTrackerEvent } from '.'; import Emittery from 'emittery'; -import { WalletProvider, ProviderError, ProviderFailure, CSL, Cardano } from '@cardano-sdk/core'; -import { TransactionError, TransactionFailure } from './TransactionError'; -import { dummyLogger, Logger } from 'ts-log'; import delay from 'delay'; -import { TransactionTrackerEvent } from '.'; export type Milliseconds = number; @@ -44,7 +44,7 @@ export class InMemoryTransactionTracker extends Emittery void 0).then(() => this.#pendingTransactions.delete(hash)); return promise; diff --git a/packages/wallet/src/InMemoryUtxoRepository.ts b/packages/wallet/src/InMemoryUtxoRepository.ts index c95d92e4310..98748bc74f5 100644 --- a/packages/wallet/src/InMemoryUtxoRepository.ts +++ b/packages/wallet/src/InMemoryUtxoRepository.ts @@ -1,12 +1,12 @@ -import { WalletProvider, Cardano, cslUtil, CSL, coreToCsl, cslToCore } from '@cardano-sdk/core'; -import { dummyLogger, Logger } from 'ts-log'; +import { CSL, Cardano, WalletProvider, coreToCsl, cslToCore, cslUtil } from '@cardano-sdk/core'; import { InputSelector, SelectionConstraints, SelectionResult } from '@cardano-sdk/cip2'; import { KeyManager } from './KeyManagement'; +import { Logger, dummyLogger } from 'ts-log'; import { - UtxoRepository, OnTransactionArgs, TransactionTracker, TransactionTrackerEvent, + UtxoRepository, UtxoRepositoryEvent, UtxoRepositoryEvents } from './types'; @@ -38,7 +38,7 @@ export class InMemoryUtxoRepository extends Emittery imple this.#logger = logger; this.#provider = provider; this.#utxoSet = new Set(); - this.#delegationAndRewards = { rewards: undefined, delegate: undefined }; + this.#delegationAndRewards = { delegate: undefined, rewards: undefined }; this.#inputSelector = inputSelector; this.#keyManager = keyManager; txTracker.on(TransactionTrackerEvent.NewTransaction, (args) => { @@ -89,10 +89,10 @@ export class InMemoryUtxoRepository extends Emittery imple await this.sync(); } return this.#inputSelector.select({ - utxo: new Set(coreToCsl.utxo(this.availableUtxos)), - outputs, constraints, - implicitCoin + implicitCoin, + outputs, + utxo: new Set(coreToCsl.utxo(this.availableUtxos)) }); } @@ -119,10 +119,10 @@ export class InMemoryUtxoRepository extends Emittery imple #emitSynced() { this.emit(UtxoRepositoryEvent.Changed, { - allUtxos: this.allUtxos, - availableUtxos: this.availableUtxos, allRewards: this.allRewards, + allUtxos: this.allUtxos, availableRewards: this.availableRewards, + availableUtxos: this.availableUtxos, delegation: this.delegation }).catch(this.#logger.error); } diff --git a/packages/wallet/src/KeyManagement/InMemoryKeyManager.ts b/packages/wallet/src/KeyManagement/InMemoryKeyManager.ts index 67821586f84..42cf86632bc 100644 --- a/packages/wallet/src/KeyManagement/InMemoryKeyManager.ts +++ b/packages/wallet/src/KeyManagement/InMemoryKeyManager.ts @@ -1,6 +1,6 @@ import * as bip39 from 'bip39'; -import { Cardano, CSL } from '@cardano-sdk/core'; import * as errors from './errors'; +import { CSL, Cardano } from '@cardano-sdk/core'; import { KeyManager } from './types'; import { harden, joinMnemonicWords } from './util'; @@ -45,6 +45,8 @@ export const createInMemoryKeyManager = ({ return baseAddr.to_address().to_bech32(); }, + publicKey: publicKey.to_raw_key(), + publicParentKey: publicParentKey.to_raw_key(), signMessage: async (_addressType, _signingIndex, message) => ({ publicKey: publicParentKey.toString(), signature: `Signature for ${message} is not implemented yet` @@ -57,8 +59,6 @@ export const createInMemoryKeyManager = ({ witnessSet.set_vkeys(vkeyWitnesses); return witnessSet; }, - stakeKey: stakeKey.to_raw_key(), - publicKey: publicKey.to_raw_key(), - publicParentKey: publicParentKey.to_raw_key() + stakeKey: stakeKey.to_raw_key() }; }; diff --git a/packages/wallet/src/KeyManagement/types.ts b/packages/wallet/src/KeyManagement/types.ts index b10546b5d4b..857ca02a2f6 100644 --- a/packages/wallet/src/KeyManagement/types.ts +++ b/packages/wallet/src/KeyManagement/types.ts @@ -1,5 +1,5 @@ -import { CSL } from '@cardano-sdk/core'; import { Address } from '..'; +import { CSL } from '@cardano-sdk/core'; export interface KeyManager { deriveAddress: (addressIndex: number, index: 0 | 1) => string; diff --git a/packages/wallet/src/SingleAddressWallet.ts b/packages/wallet/src/SingleAddressWallet.ts index fa10609edf8..1ce3242eef7 100644 --- a/packages/wallet/src/SingleAddressWallet.ts +++ b/packages/wallet/src/SingleAddressWallet.ts @@ -1,9 +1,9 @@ -import { WalletProvider, ProviderError, CSL, coreToCsl, Cardano } from '@cardano-sdk/core'; +import { BalanceTracker, KeyManagement, TransactionError, TransactionFailure, TransactionTracker } from '.'; +import { CSL, Cardano, ProviderError, WalletProvider, coreToCsl } from '@cardano-sdk/core'; +import { InitializeTxProps, TxInternals, computeImplicitCoin, createTransactionInternals } from './Transaction'; +import { Logger, dummyLogger } from 'ts-log'; import { UtxoRepository } from './types'; -import { dummyLogger, Logger } from 'ts-log'; import { defaultSelectionConstraints } from '@cardano-sdk/cip2'; -import { computeImplicitCoin, createTransactionInternals, InitializeTxProps, TxInternals } from './Transaction'; -import { BalanceTracker, KeyManagement, TransactionError, TransactionFailure, TransactionTracker } from '.'; export interface SubmitTxResult { /** @@ -71,7 +71,6 @@ export const createSingleAddressWallet = async ( const validityInterval = ensureValidityInterval(tip.slot, props.options?.validityInterval); const txOutputs = new Set([...props.outputs].map((output) => coreToCsl.txOut(output))); const constraints = defaultSelectionConstraints({ - protocolParameters, buildTx: async (inputSelection) => { logger.debug('Building TX for selection constraints', inputSelection); const { body, hash } = await createTransactionInternals({ @@ -80,7 +79,8 @@ export const createSingleAddressWallet = async ( validityInterval }); return signTx(body, hash); - } + }, + protocolParameters }); const implicitCoin = computeImplicitCoin(protocolParameters, props); const inputSelectionResult = await utxoRepository.selectInputs(txOutputs, constraints, implicitCoin); @@ -101,8 +101,8 @@ export const createSingleAddressWallet = async ( }); const confirmed = txTracker.track(tx, submitted); return { - submitted, - confirmed + confirmed, + submitted }; } }; diff --git a/packages/wallet/src/Transaction/CertificateFactory.ts b/packages/wallet/src/Transaction/CertificateFactory.ts index f2cfab92774..8daf71d6771 100644 --- a/packages/wallet/src/Transaction/CertificateFactory.ts +++ b/packages/wallet/src/Transaction/CertificateFactory.ts @@ -1,4 +1,4 @@ -import { NotImplementedError, Cardano, CSL } from '@cardano-sdk/core'; +import { CSL, Cardano, NotImplementedError } from '@cardano-sdk/core'; import { KeyManager } from '../KeyManagement'; export type Ed25519KeyHashBech32 = string; diff --git a/packages/wallet/src/Transaction/createTransactionInternals.ts b/packages/wallet/src/Transaction/createTransactionInternals.ts index 1666cdd5ff2..14ae511025b 100644 --- a/packages/wallet/src/Transaction/createTransactionInternals.ts +++ b/packages/wallet/src/Transaction/createTransactionInternals.ts @@ -1,5 +1,5 @@ -import { SelectionResult } from '@cardano-sdk/cip2'; import { CSL, Cardano } from '@cardano-sdk/core'; +import { SelectionResult } from '@cardano-sdk/cip2'; import { Withdrawal } from './withdrawal'; export type TxInternals = { diff --git a/packages/wallet/src/Transaction/withdrawal.ts b/packages/wallet/src/Transaction/withdrawal.ts index 11385640a9c..b2228a1ae25 100644 --- a/packages/wallet/src/Transaction/withdrawal.ts +++ b/packages/wallet/src/Transaction/withdrawal.ts @@ -1,4 +1,4 @@ -import { Cardano, CSL } from '@cardano-sdk/core'; +import { CSL, Cardano } from '@cardano-sdk/core'; import { KeyManager } from '../KeyManagement'; export type Withdrawal = { diff --git a/packages/wallet/src/types.ts b/packages/wallet/src/types.ts index 1f78f73ae23..1b6a8f3ddb3 100644 --- a/packages/wallet/src/types.ts +++ b/packages/wallet/src/types.ts @@ -1,5 +1,5 @@ +import { CSL, Cardano } from '@cardano-sdk/core'; import { SelectionConstraints, SelectionResult } from '@cardano-sdk/cip2'; -import { Cardano, CSL } from '@cardano-sdk/core'; import Emittery from 'emittery'; export enum UtxoRepositoryEvent { diff --git a/packages/wallet/test/BalanceTracker.test.ts b/packages/wallet/test/BalanceTracker.test.ts index d4c0f19ab7f..add74e94ba4 100644 --- a/packages/wallet/test/BalanceTracker.test.ts +++ b/packages/wallet/test/BalanceTracker.test.ts @@ -1,6 +1,6 @@ -import { MockUtxoRepository } from './mocks'; import { BalanceTracker, UtxoRepositoryEvent, UtxoRepositoryFields } from '../src'; import { Cardano } from '@cardano-sdk/core'; +import { MockUtxoRepository } from './mocks'; const numAssets = (tokenMap?: Cardano.TokenMap) => Object.keys(tokenMap || {}).length; @@ -25,10 +25,10 @@ describe('BalanceTracker', () => { const allRewards = utxoRepository.allRewards - 1n; const availableRewards = utxoRepository.allRewards - 2n; await utxoRepository.emit(UtxoRepositoryEvent.Changed, { - allUtxos: utxoRepository.allUtxos.slice(1), - availableUtxos: utxoRepository.allUtxos.slice(2), allRewards, + allUtxos: utxoRepository.allUtxos.slice(1), availableRewards, + availableUtxos: utxoRepository.allUtxos.slice(2), delegation: null } as UtxoRepositoryFields); diff --git a/packages/wallet/test/InMemoryTransactionTracker.test.ts b/packages/wallet/test/InMemoryTransactionTracker.test.ts index 87d291c69b4..974b97028de 100644 --- a/packages/wallet/test/InMemoryTransactionTracker.test.ts +++ b/packages/wallet/test/InMemoryTransactionTracker.test.ts @@ -1,8 +1,8 @@ -import { ProviderError, ProviderFailure, CSL } from '@cardano-sdk/core'; +import { CSL, ProviderError, ProviderFailure } from '@cardano-sdk/core'; +import { InMemoryTransactionTracker, TransactionFailure, TransactionTrackerEvent } from '../src'; +import { ProviderStub, ledgerTip, providerStub, queryTransactionsResult } from './mocks'; import { dummyLogger } from 'ts-log'; -import { ledgerTip, providerStub, ProviderStub, queryTransactionsResult } from './mocks'; import mockDelay from 'delay'; -import { TransactionTrackerEvent, InMemoryTransactionTracker, TransactionFailure } from '../src'; jest.mock('delay', () => jest.fn().mockResolvedValue(void 0)); // eslint-disable-next-line sonarjs/no-duplicate-string @@ -30,9 +30,9 @@ describe('InMemoryTransactionTracker', () => { provider.queryTransactionsByHashes.mockReturnValue([queryTransactionsResult[0]]); mockHashTransactionReturn('some-hash'); txTracker = new InMemoryTransactionTracker({ - provider, logger: dummyLogger, - pollInterval: POLL_INTERVAL + pollInterval: POLL_INTERVAL, + provider }); ledgerTipSlot = ledgerTip.slot; (mockDelay as unknown as jest.Mock).mockReset(); diff --git a/packages/wallet/test/InMemoryUtxoRepository.test.ts b/packages/wallet/test/InMemoryUtxoRepository.test.ts index 72c4476d9d9..2dd401d923b 100644 --- a/packages/wallet/test/InMemoryUtxoRepository.test.ts +++ b/packages/wallet/test/InMemoryUtxoRepository.test.ts @@ -1,17 +1,6 @@ /* eslint-disable unicorn/consistent-function-scoping */ /* eslint-disable promise/param-names */ -import { roundRobinRandomImprove, InputSelector } from '@cardano-sdk/cip2'; -import { Cardano, CSL, coreToCsl } from '@cardano-sdk/core'; -import { flushPromises, SelectionConstraints } from '@cardano-sdk/util-dev'; -import { - providerStub, - delegate, - rewards, - ProviderStub, - utxo, - delegationAndRewards, - MockTransactionTracker -} from './mocks'; +import { CSL, Cardano, coreToCsl } from '@cardano-sdk/core'; import { InMemoryUtxoRepository, KeyManagement, @@ -20,6 +9,17 @@ import { UtxoRepositoryEvent, UtxoRepositoryFields } from '../src'; +import { InputSelector, roundRobinRandomImprove } from '@cardano-sdk/cip2'; +import { + MockTransactionTracker, + ProviderStub, + delegate, + delegationAndRewards, + providerStub, + rewards, + utxo +} from './mocks'; +import { SelectionConstraints, flushPromises } from '@cardano-sdk/util-dev'; import { TransactionError, TransactionFailure } from '../src/TransactionError'; const addresses = [ @@ -54,9 +54,9 @@ describe('InMemoryUtxoRepository', () => { ]); txTracker = new MockTransactionTracker(); utxoRepository = new InMemoryUtxoRepository({ - provider, - keyManager, inputSelector, + keyManager, + provider, txTracker }); }); @@ -72,10 +72,10 @@ describe('InMemoryUtxoRepository', () => { utxoRepository.on(UtxoRepositoryEvent.Changed, syncedHandler); await utxoRepository.sync(); const expectedFields: UtxoRepositoryFields = { - allUtxos: utxo, - availableUtxos: utxo, allRewards: rewards, + allUtxos: utxo, availableRewards: rewards, + availableUtxos: utxo, delegation: delegate }; expect(utxoRepository).toMatchObject(expectedFields); @@ -83,8 +83,8 @@ describe('InMemoryUtxoRepository', () => { expect(syncedHandler).toBeCalledWith(expectedFields); const identicalUtxo = [{ ...utxo[1][0] }, { ...utxo[1][1] }] as const; // clone UTxO provider.utxoDelegationAndRewards.mockResolvedValueOnce({ - utxo: [utxo[0], identicalUtxo], - delegationAndRewards + delegationAndRewards, + utxo: [utxo[0], identicalUtxo] }); await utxoRepository.sync(); expect(utxoRepository.allUtxos.length).toBe(2); @@ -119,18 +119,18 @@ describe('InMemoryUtxoRepository', () => { const syncedHandler = jest.fn(); utxoRepository.on(UtxoRepositoryEvent.Changed, syncedHandler); await txTracker.emit(TransactionTrackerEvent.NewTransaction, { - transaction, - confirmed + confirmed, + transaction }); // transaction not yet confirmed expect(utxoRepository.availableUtxos).toHaveLength(utxoRepository.allUtxos.length - 1); expect(utxoRepository.availableUtxos).not.toContain(transactionUtxo); expect(syncedHandler).toBeCalledTimes(1); expect(syncedHandler).toBeCalledWith({ - allUtxos: utxo, - availableUtxos: utxo.slice(1), allRewards: rewards, + allUtxos: utxo, availableRewards: rewards - transactionWithdrawal, + availableUtxos: utxo.slice(1), delegation: delegate } as UtxoRepositoryFields); }; @@ -145,20 +145,20 @@ describe('InMemoryUtxoRepository', () => { transaction = { body: () => ({ inputs: () => ({ - len: () => 1, - get: () => coreToCsl.txIn(transactionUtxo[0]) + get: () => coreToCsl.txIn(transactionUtxo[0]), + len: () => 1 }), withdrawals: () => ({ + get: () => CSL.BigNum.from_str(transactionWithdrawal.toString()), keys: () => ({ - len: () => 1, get: () => CSL.RewardAddress.new( Cardano.NetworkId.testnet, CSL.StakeCredential.from_keyhash(keyManager.stakeKey.hash()) - ) + ), + len: () => 1 }), - len: () => 1, - get: () => CSL.BigNum.from_str(transactionWithdrawal.toString()) + len: () => 1 }) }) } as unknown as CSL.Transaction; @@ -180,11 +180,11 @@ describe('InMemoryUtxoRepository', () => { // Simulate spent utxo and rewards expect(provider.utxoDelegationAndRewards).toBeCalledTimes(1); provider.utxoDelegationAndRewards.mockResolvedValueOnce({ - utxo: utxo.slice(1), delegationAndRewards: { ...delegationAndRewards, rewards: rewards - transactionWithdrawal - } + }, + utxo: utxo.slice(1) }); }); diff --git a/packages/wallet/test/KeyManagement/InMemoryKeyManager.test.ts b/packages/wallet/test/KeyManagement/InMemoryKeyManager.test.ts index 927f77cc284..19dba49ee50 100644 --- a/packages/wallet/test/KeyManagement/InMemoryKeyManager.test.ts +++ b/packages/wallet/test/KeyManagement/InMemoryKeyManager.test.ts @@ -1,4 +1,4 @@ -import { Cardano, CSL } from '@cardano-sdk/core'; +import { CSL, Cardano } from '@cardano-sdk/core'; import { KeyManagement } from '../../src'; describe('InMemoryKeyManager', () => { diff --git a/packages/wallet/test/SingleAddressWallet.test.ts b/packages/wallet/test/SingleAddressWallet.test.ts index 0e460a211ee..ad0cae6c7cf 100644 --- a/packages/wallet/test/SingleAddressWallet.test.ts +++ b/packages/wallet/test/SingleAddressWallet.test.ts @@ -1,16 +1,16 @@ /* eslint-disable max-len */ -import { Cardano, CSL } from '@cardano-sdk/core'; -import { InputSelector, roundRobinRandomImprove } from '@cardano-sdk/cip2'; -import { ProviderStub, providerStub, txTracker } from './mocks'; import { BalanceTracker, - createSingleAddressWallet, InMemoryUtxoRepository, KeyManagement, SingleAddressWallet, SingleAddressWalletDependencies, - UtxoRepository + UtxoRepository, + createSingleAddressWallet } from '../src'; +import { CSL, Cardano } from '@cardano-sdk/core'; +import { InputSelector, roundRobinRandomImprove } from '@cardano-sdk/cip2'; +import { ProviderStub, providerStub, txTracker } from './mocks'; describe('Wallet', () => { const name = 'Test Wallet'; @@ -28,8 +28,8 @@ describe('Wallet', () => { }); provider = providerStub(); inputSelector = roundRobinRandomImprove(); - utxoRepository = new InMemoryUtxoRepository({ provider, keyManager, inputSelector, txTracker }); - walletDependencies = { keyManager, provider, utxoRepository, txTracker }; + utxoRepository = new InMemoryUtxoRepository({ inputSelector, keyManager, provider, txTracker }); + walletDependencies = { keyManager, provider, txTracker, utxoRepository }; }); test('createWallet', async () => { diff --git a/packages/wallet/test/Transaction/CertificateFactory.test.ts b/packages/wallet/test/Transaction/CertificateFactory.test.ts index ac8a5e0f933..1ee438929c5 100644 --- a/packages/wallet/test/Transaction/CertificateFactory.test.ts +++ b/packages/wallet/test/Transaction/CertificateFactory.test.ts @@ -1,6 +1,6 @@ -import { testKeyManager } from '../mocks'; import { CertificateFactory } from '../../src/Transaction'; import { KeyManager } from '../../src/KeyManagement'; +import { testKeyManager } from '../mocks'; describe('Transaction.CertificateFactory', () => { let stakeKey: string; @@ -41,22 +41,22 @@ describe('Transaction.CertificateFactory', () => { const params = certs .poolRegistration({ cost: 1000n, - pledge: 10_000n, margin: { denominator: 5, numerator: 1 }, owners: [owner], + pledge: 10_000n, poolKeyHash: stakeKey, + poolMetadata, relays: [ - { relayType: 'singlehost-name', hostname: 'example.com', port: 5000 }, + { hostname: 'example.com', port: 5000, relayType: 'singlehost-name' }, { - relayType: 'singlehost-addr', + ipv4: '127.0.0.1', port: 6000, - ipv4: '127.0.0.1' + relayType: 'singlehost-addr' }, - { relayType: 'multihost-name', dnsName: 'example.com' } + { dnsName: 'example.com', relayType: 'multihost-name' } ], - vrfKeyHash, rewardAddress, - poolMetadata + vrfKeyHash }) .as_pool_registration()! .pool_params(); diff --git a/packages/wallet/test/Transaction/computeImplicitCoin.test.ts b/packages/wallet/test/Transaction/computeImplicitCoin.test.ts index 30870d3f905..6e8409a55ae 100644 --- a/packages/wallet/test/Transaction/computeImplicitCoin.test.ts +++ b/packages/wallet/test/Transaction/computeImplicitCoin.test.ts @@ -1,11 +1,11 @@ +import { InitializeTxProps } from '../../src/Transaction'; import { ProtocolParametersRequiredByWallet } from '@cardano-sdk/core'; -import { testKeyManager } from '../mocks'; import { Transaction } from '../../src'; -import { InitializeTxProps } from '../../src/Transaction'; +import { testKeyManager } from '../mocks'; describe('Transaction.computeImplicitCoin', () => { it('sums registrations for deposit, withdrawals and deregistrations for input', async () => { - const protocolParameters = { stakeKeyDeposit: 2, poolDeposit: 3 } as ProtocolParametersRequiredByWallet; + const protocolParameters = { poolDeposit: 3, stakeKeyDeposit: 2 } as ProtocolParametersRequiredByWallet; const keyManager = testKeyManager(); const certs = new Transaction.CertificateFactory(keyManager); const certificates = [ diff --git a/packages/wallet/test/Transaction/createTransactionInternals.test.ts b/packages/wallet/test/Transaction/createTransactionInternals.test.ts index 4c60f2cb7ae..8795ecdfccc 100644 --- a/packages/wallet/test/Transaction/createTransactionInternals.test.ts +++ b/packages/wallet/test/Transaction/createTransactionInternals.test.ts @@ -1,14 +1,14 @@ -import { InputSelector, roundRobinRandomImprove } from '@cardano-sdk/cip2'; -import { WalletProvider, CSL, coreToCsl } from '@cardano-sdk/core'; -import { SelectionConstraints } from '@cardano-sdk/util-dev'; -import { MockTransactionTracker, providerStub, testKeyManager } from '../mocks'; +import { CSL, WalletProvider, coreToCsl } from '@cardano-sdk/core'; import { CertificateFactory, - createTransactionInternals, CreateTxInternalsProps, - Withdrawal + Withdrawal, + createTransactionInternals } from '../../src/Transaction'; -import { UtxoRepository, InMemoryUtxoRepository, KeyManagement } from '../../src'; +import { InMemoryUtxoRepository, KeyManagement, UtxoRepository } from '../../src'; +import { InputSelector, roundRobinRandomImprove } from '@cardano-sdk/cip2'; +import { MockTransactionTracker, providerStub, testKeyManager } from '../mocks'; +import { SelectionConstraints } from '@cardano-sdk/util-dev'; const address = 'addr_test1qq585l3hyxgj3nas2v3xymd23vvartfhceme6gv98aaeg9muzcjqw982pcftgx53fu5527z2cj2tkx2h8ux2vxsg475q2g7k3g'; @@ -49,9 +49,9 @@ describe('Transaction.createTransactionInternals', () => { }) ]); utxoRepository = new InMemoryUtxoRepository({ - provider, - keyManager, inputSelector, + keyManager, + provider, txTracker: new MockTransactionTracker() }); }); diff --git a/packages/wallet/test/Transaction/withdrawal.test.ts b/packages/wallet/test/Transaction/withdrawal.test.ts index 0e6f5a547e9..9d5b4018ce1 100644 --- a/packages/wallet/test/Transaction/withdrawal.test.ts +++ b/packages/wallet/test/Transaction/withdrawal.test.ts @@ -1,6 +1,6 @@ import { CSL } from '@cardano-sdk/core'; -import { testKeyManager } from '../mocks'; import { Transaction } from '../../src'; +import { testKeyManager } from '../mocks'; describe('Transaction.withdrawal', () => { it('creates objects of correct types', async () => { diff --git a/packages/wallet/test/integration/withdrawal.test.ts b/packages/wallet/test/integration/withdrawal.test.ts index 47f89827522..209b9bef7a0 100644 --- a/packages/wallet/test/integration/withdrawal.test.ts +++ b/packages/wallet/test/integration/withdrawal.test.ts @@ -1,9 +1,6 @@ /* eslint-disable no-fallthrough */ -import { roundRobinRandomImprove } from '@cardano-sdk/cip2'; -import { Cardano } from '@cardano-sdk/core'; import { BalanceTrackerEvent, - createSingleAddressWallet, InMemoryTransactionTracker, InMemoryUtxoRepository, KeyManagement, @@ -14,10 +11,13 @@ import { TransactionFailure, TransactionTracker, UtxoRepository, - UtxoRepositoryEvent + UtxoRepositoryEvent, + createSingleAddressWallet } from '@cardano-sdk/wallet'; -// Not testing with a real provider +import { Cardano } from '@cardano-sdk/core'; import { providerStub } from '../mocks'; +import { roundRobinRandomImprove } from '@cardano-sdk/cip2'; +// Not testing with a real provider const walletProps: SingleAddressWalletProps = { name: 'some-wallet' }; const networkId = Cardano.NetworkId.mainnet; @@ -31,16 +31,16 @@ describe('integration/withdrawal', () => { let wallet: SingleAddressWallet; beforeAll(async () => { - keyManager = KeyManagement.createInMemoryKeyManager({ mnemonicWords, password, networkId }); + keyManager = KeyManagement.createInMemoryKeyManager({ mnemonicWords, networkId, password }); const provider = providerStub(); const inputSelector = roundRobinRandomImprove(); - txTracker = new InMemoryTransactionTracker({ provider, pollInterval: 1 }); - utxoRepository = new InMemoryUtxoRepository({ provider, txTracker, inputSelector, keyManager }); + txTracker = new InMemoryTransactionTracker({ pollInterval: 1, provider }); + utxoRepository = new InMemoryUtxoRepository({ inputSelector, keyManager, provider, txTracker }); wallet = await createSingleAddressWallet(walletProps, { keyManager, provider, - utxoRepository, - txTracker + txTracker, + utxoRepository }); // Call this to sync available balance @@ -70,8 +70,9 @@ describe('integration/withdrawal', () => { const { body, hash } = await wallet.initializeTx({ certificates: [certFactory.stakeKeyDeregistration()], - withdrawals: [Transaction.withdrawal(keyManager, utxoRepository.availableRewards || 0n)], - outputs: new Set() // In a real transaction you would probably want to have some outputs + outputs: new Set(), + // In a real transaction you would probably want to have some outputs + withdrawals: [Transaction.withdrawal(keyManager, utxoRepository.availableRewards || 0n)] }); // Calculated fee is returned by invoking body.fee() const tx = await wallet.signTx(body, hash); diff --git a/packages/wallet/test/mocks/MockTransactionTracker.ts b/packages/wallet/test/mocks/MockTransactionTracker.ts index 13961761336..a1b3ce1fa69 100644 --- a/packages/wallet/test/mocks/MockTransactionTracker.ts +++ b/packages/wallet/test/mocks/MockTransactionTracker.ts @@ -1,5 +1,5 @@ -import Emittery from 'emittery'; import { TransactionTrackerEvents } from '../../src'; +import Emittery from 'emittery'; export class MockTransactionTracker extends Emittery { track = jest.fn(); diff --git a/packages/wallet/test/mocks/MockUtxoRepository.ts b/packages/wallet/test/mocks/MockUtxoRepository.ts index 97cc972fbbf..3d32ef72f5d 100644 --- a/packages/wallet/test/mocks/MockUtxoRepository.ts +++ b/packages/wallet/test/mocks/MockUtxoRepository.ts @@ -1,6 +1,6 @@ -import Emittery from 'emittery'; -import { delegate, rewards, utxo } from './ProviderStub'; import { UtxoRepository, UtxoRepositoryEvents } from '../../src'; +import { delegate, rewards, utxo } from './ProviderStub'; +import Emittery from 'emittery'; export class MockUtxoRepository extends Emittery implements UtxoRepository { sync = jest.fn().mockResolvedValue(void 0); diff --git a/packages/wallet/test/mocks/ProviderStub.ts b/packages/wallet/test/mocks/ProviderStub.ts index dc072bf5543..ebd3e17216b 100644 --- a/packages/wallet/test/mocks/ProviderStub.ts +++ b/packages/wallet/test/mocks/ProviderStub.ts @@ -9,18 +9,18 @@ export const utxo: Cardano.Utxo[] = [ { address: 'addr_test1qq585l3hyxgj3nas2v3xymd23vvartfhceme6gv98aaeg9muzcjqw982pcftgx53fu5527z2cj2tkx2h8ux2vxsg475q2g7k3g', - txId: 'bb217abaca60fc0ca68c1555eca6a96d2478547818ae76ce6836133f3cc546e0', - index: 1 + index: 1, + txId: 'bb217abaca60fc0ca68c1555eca6a96d2478547818ae76ce6836133f3cc546e0' }, { address: 'addr_test1qzs0umu0s2ammmpw0hea0w2crtcymdjvvlqngpgqy76gpfnuzcjqw982pcftgx53fu5527z2cj2tkx2h8ux2vxsg475qp3y3vz', value: { - coins: 4_027_026_465n, assets: { - [TSLA]: 10n, - [PXL]: 5n - } + [PXL]: 5n, + [TSLA]: 10n + }, + coins: 4_027_026_465n } } ], @@ -28,17 +28,17 @@ export const utxo: Cardano.Utxo[] = [ { address: 'addr_test1qzs0umu0s2ammmpw0hea0w2crtcymdjvvlqngpgqy76gpfnuzcjqw982pcftgx53fu5527z2cj2tkx2h8ux2vxsg475qp3y3vz', - txId: 'c7c0973c6bbf1a04a9f306da7814b4fa564db649bf48b0bd93c273bd03143547', - index: 0 + index: 0, + txId: 'c7c0973c6bbf1a04a9f306da7814b4fa564db649bf48b0bd93c273bd03143547' }, { address: 'addr_test1qq585l3hyxgj3nas2v3xymd23vvartfhceme6gv98aaeg9muzcjqw982pcftgx53fu5527z2cj2tkx2h8ux2vxsg475q2g7k3g', value: { - coins: 3_289_566n, assets: { [TSLA]: 15n - } + }, + coins: 3_289_566n } } ], @@ -46,8 +46,8 @@ export const utxo: Cardano.Utxo[] = [ { address: 'addr_test1qq585l3hyxgj3nas2v3xymd23vvartfhceme6gv98aaeg9muzcjqw982pcftgx53fu5527z2cj2tkx2h8ux2vxsg475q2g7k3g', - txId: 'ea1517b8c36fea3148df9aa1f49bbee66ff59a5092331a67bd8b3c427e1d79d7', - index: 2 + index: 2, + txId: 'ea1517b8c36fea3148df9aa1f49bbee66ff59a5092331a67bd8b3c427e1d79d7' }, { address: @@ -70,8 +70,8 @@ export const queryTransactionsResult: Cardano.TxAlonzo[] = [ { address: 'addr_test1qpfhhfy2qgls50r9u4yh0l7z67xpg0a5rrhkmvzcuqrd0znuzcjqw982pcftgx53fu5527z2cj2tkx2h8ux2vxsg475q9gw0lz', - txId: 'bb217abaca60fc0ca68c1555eca6a96d2478547818ae76ce6836133f3cc546e0', - index: 0 + index: 0, + txId: 'bb217abaca60fc0ca68c1555eca6a96d2478547818ae76ce6836133f3cc546e0' } ], outputs: [ @@ -108,15 +108,27 @@ export const ledgerTip = { * returns WalletProvider-compatible object */ export const providerStub = () => ({ + currentWalletProtocolParameters: async () => ({ + coinsPerUtxoWord: 34_482, + maxCollateralInputs: 1, + maxTxSize: 16_384, + maxValueSize: 1000, + minFeeCoefficient: 44, + minFeeConstant: 155_381, + minPoolCost: 340_000_000, + poolDeposit: 500_000_000, + protocolVersion: { major: 5, minor: 0 }, + stakeKeyDeposit: 2_000_000 + }), ledgerTip: jest.fn().mockResolvedValue(ledgerTip), networkInfo: async () => ({ currentEpoch: { + end: { + date: new Date(1_632_687_616) + }, number: 158, start: { date: new Date(1_632_255_616) - }, - end: { - date: new Date(1_632_687_616) } }, lovelaceSupply: { @@ -129,7 +141,9 @@ export const providerStub = () => ({ live: 15_001_884_895_856_815n } }), - submitTx: jest.fn().mockResolvedValue(void 0), + queryTransactionsByAddresses: queryTransactions(), + queryTransactionsByHashes: queryTransactions(), + stakePoolMetadata: jest.fn(), stakePoolStats: async () => ({ qty: { active: 1000, @@ -137,23 +151,9 @@ export const providerStub = () => ({ retiring: 5 } }), - utxoDelegationAndRewards: jest.fn().mockResolvedValue({ utxo, delegationAndRewards }), - queryTransactionsByAddresses: queryTransactions(), - queryTransactionsByHashes: queryTransactions(), - currentWalletProtocolParameters: async () => ({ - minFeeCoefficient: 44, - minFeeConstant: 155_381, - stakeKeyDeposit: 2_000_000, - poolDeposit: 500_000_000, - protocolVersion: { major: 5, minor: 0 }, - minPoolCost: 340_000_000, - maxTxSize: 16_384, - maxValueSize: 1000, - maxCollateralInputs: 1, - coinsPerUtxoWord: 34_482 - }), stakePools: jest.fn(), - stakePoolMetadata: jest.fn() + submitTx: jest.fn().mockResolvedValue(void 0), + utxoDelegationAndRewards: jest.fn().mockResolvedValue({ delegationAndRewards, utxo }) }); export type ProviderStub = ReturnType; diff --git a/packages/wallet/test/mocks/testKeyManager.ts b/packages/wallet/test/mocks/testKeyManager.ts index 9ec2c06c85d..06d6f501806 100644 --- a/packages/wallet/test/mocks/testKeyManager.ts +++ b/packages/wallet/test/mocks/testKeyManager.ts @@ -4,6 +4,6 @@ import { KeyManagement } from '../../src'; export const testKeyManager = () => KeyManagement.createInMemoryKeyManager({ mnemonicWords: KeyManagement.util.generateMnemonicWords(), - password: '', - networkId: Cardano.NetworkId.testnet + networkId: Cardano.NetworkId.testnet, + password: '' }); diff --git a/yarn.lock b/yarn.lock index ecb47e83e98..37c740aa4f1 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2680,6 +2680,11 @@ acorn-globals@^6.0.0: acorn "^7.1.1" acorn-walk "^7.1.1" +acorn-jsx@^5.2.0: + version "5.3.2" + resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.3.2.tgz#7ed5bb55908b3b2f1bc55c6af1653bada7f07937" + integrity sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ== + acorn-jsx@^5.3.1: version "5.3.1" resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.3.1.tgz#fc8661e11b7ac1539c47dbfea2e72b3af34d267b" @@ -4518,6 +4523,21 @@ eslint-plugin-sonarjs@^0.9.1: resolved "https://registry.yarnpkg.com/eslint-plugin-sonarjs/-/eslint-plugin-sonarjs-0.9.1.tgz#a3c63ab0d267bfb69863159e42c8081b01fd3ac6" integrity sha512-KKFofk1LPjGHWeAZijYWv32c/C4mz+OAeBNVxhxHu1hknrTOhu415MWC8qKdAdsmOlBPShs9evM4mI1o7MNMhw== +eslint-plugin-sort-imports-es6-autofix@^0.6.0: + version "0.6.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-sort-imports-es6-autofix/-/eslint-plugin-sort-imports-es6-autofix-0.6.0.tgz#b8cd8639d7a54cefce6b17898b102fd5ec31e52b" + integrity sha512-2NVaBGF9NN+727Fyq+jJYihdIeegjXeUUrZED9Q8FVB8MsV3YQEyXG96GVnXqWt0pmn7xfCZOZf3uKnIhBrfeQ== + +eslint-plugin-sort-keys-fix@^1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/eslint-plugin-sort-keys-fix/-/eslint-plugin-sort-keys-fix-1.1.2.tgz#00c8b5791612ec32162b8d7a0563e9c6eb27ec59" + integrity sha512-DNPHFGCA0/hZIsfODbeLZqaGY/+q3vgtshF85r+YWDNCQ2apd9PNs/zL6ttKm0nD1IFwvxyg3YOTI7FHl4unrw== + dependencies: + espree "^6.1.2" + esutils "^2.0.2" + natural-compare "^1.4.0" + requireindex "~1.2.0" + eslint-plugin-unicorn@^35.0.0: version "35.0.0" resolved "https://registry.yarnpkg.com/eslint-plugin-unicorn/-/eslint-plugin-unicorn-35.0.0.tgz#40797793d4f645bafaaa7a1396b8f4ca7b2a7dbd" @@ -4643,6 +4663,15 @@ eslint@^7.32.0: text-table "^0.2.0" v8-compile-cache "^2.0.3" +espree@^6.1.2: + version "6.2.1" + resolved "https://registry.yarnpkg.com/espree/-/espree-6.2.1.tgz#77fc72e1fd744a2052c20f38a5b575832e82734a" + integrity sha512-ysCxRQY3WaXJz9tdbWOwuWr5Y/XrPTGX9Kiz3yoUXwW0VZ4w30HTkQLaGx/+ttFjF8i+ACbArnB4ce68a9m5hw== + dependencies: + acorn "^7.1.1" + acorn-jsx "^5.2.0" + eslint-visitor-keys "^1.1.0" + espree@^7.3.0, espree@^7.3.1: version "7.3.1" resolved "https://registry.yarnpkg.com/espree/-/espree-7.3.1.tgz#f2df330b752c6f55019f8bd89b7660039c1bbbb6" @@ -8803,6 +8832,11 @@ require-main-filename@^2.0.0: resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-2.0.0.tgz#d0b329ecc7cc0f61649f62215be69af54aa8989b" integrity sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg== +requireindex@~1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/requireindex/-/requireindex-1.2.0.tgz#3463cdb22ee151902635aa6c9535d4de9c2ef1ef" + integrity sha512-L9jEkOi3ASd9PYit2cwRfyppc9NoABujTP8/5gFcbERmo5jUoAKovIC3fsF17pkTnGsrByysqX+Kxd2OTNI1ww== + resolve-alpn@^1.0.0: version "1.2.0" resolved "https://registry.yarnpkg.com/resolve-alpn/-/resolve-alpn-1.2.0.tgz#058bb0888d1cd4d12474e9a4b6eb17bdd5addc44"