Skip to content

Commit

Permalink
refactor: inject the csl instance in ogmiosToCsl
Browse files Browse the repository at this point in the history
  • Loading branch information
rhyslbw committed Sep 24, 2021
1 parent 5c05b9d commit e9a2421
Show file tree
Hide file tree
Showing 8 changed files with 68 additions and 67 deletions.
4 changes: 1 addition & 3 deletions packages/cip2/src/util.ts
@@ -1,5 +1,5 @@
// TODO: move these utils to either core package.
// Current impelmentation of ogmiosToCsl.value() uses number instead of bigint for lovelace.
// Current implementation of ogmiosToCsl.value() uses number instead of bigint for lovelace.
// These utils should be moved after CSL is updated to use bigint.
import { CardanoSerializationLib, CSL } from '@cardano-sdk/cardano-serialization-lib';
import { Asset, Ogmios } from '@cardano-sdk/core';
Expand Down Expand Up @@ -42,8 +42,6 @@ export const valueToValueQuantities = (value: CSL.Value): ValueQuantities => {
};

// This is equivalent to ogmiosToCsl.value(), so they should be merged.
// Note that current implementation of ogmiosToCsl
// imports nodejs version of CSL, so it cannot be used in browser.
export const valueQuantitiesToValue = ({ coins, assets }: ValueQuantities, csl: CardanoSerializationLib): CSL.Value => {
const value = csl.Value.new(csl.BigNum.from_str(coins.toString()));
if (!assets) {
Expand Down
26 changes: 14 additions & 12 deletions packages/core/src/Ogmios/ogmiosToCsl.ts
@@ -1,34 +1,36 @@
import { CSL } from '@cardano-sdk/cardano-serialization-lib';
import { CardanoSerializationLib, CSL } from '@cardano-sdk/cardano-serialization-lib';
import OgmiosSchema from '@cardano-ogmios/schema';
import * as Asset from '../Asset';

export const ogmiosToCsl = {
export const ogmiosToCsl = (csl: CardanoSerializationLib) => ({
txIn: (ogmios: OgmiosSchema.TxIn): CSL.TransactionInput =>
CSL.TransactionInput.new(CSL.TransactionHash.from_bytes(Buffer.from(ogmios.txId, 'hex')), ogmios.index),
csl.TransactionInput.new(csl.TransactionHash.from_bytes(Buffer.from(ogmios.txId, 'hex')), ogmios.index),
txOut: (ogmios: OgmiosSchema.TxOut): CSL.TransactionOutput =>
CSL.TransactionOutput.new(CSL.Address.from_bech32(ogmios.address), ogmiosToCsl.value(ogmios.value)),
csl.TransactionOutput.new(csl.Address.from_bech32(ogmios.address), ogmiosToCsl(csl).value(ogmios.value)),
utxo: (ogmios: OgmiosSchema.Utxo): CSL.TransactionUnspentOutput[] =>
ogmios.map((item) => CSL.TransactionUnspentOutput.new(ogmiosToCsl.txIn(item[0]), ogmiosToCsl.txOut(item[1]))),
ogmios.map((item) =>
csl.TransactionUnspentOutput.new(ogmiosToCsl(csl).txIn(item[0]), ogmiosToCsl(csl).txOut(item[1]))
),
value: (ogmios: OgmiosSchema.Value): CSL.Value => {
const value = CSL.Value.new(CSL.BigNum.from_str(ogmios.coins.toString()));
const value = csl.Value.new(csl.BigNum.from_str(ogmios.coins.toString()));
const assets = ogmios.assets !== undefined ? Object.entries(ogmios.assets) : [];
if (assets.length === 0) {
return value;
}
const multiAsset = CSL.MultiAsset.new();
const multiAsset = csl.MultiAsset.new();
const policies = [...new Set(assets.map(([assetId]) => Asset.util.policyIdFromAssetId(assetId)))];
for (const policy of policies) {
const policyAssets = assets.filter(([assetId]) => Asset.util.policyIdFromAssetId(assetId) === policy);
const wasmAssets = CSL.Assets.new();
const wasmAssets = csl.Assets.new();
for (const [assetId, assetQuantity] of policyAssets) {
wasmAssets.insert(
CSL.AssetName.new(Buffer.from(Asset.util.assetNameFromAssetId(assetId), 'hex')),
CSL.BigNum.from_str(assetQuantity.toString())
csl.AssetName.new(Buffer.from(Asset.util.assetNameFromAssetId(assetId), 'hex')),
csl.BigNum.from_str(assetQuantity.toString())
);
}
multiAsset.insert(CSL.ScriptHash.from_bytes(Buffer.from(policy, 'hex')), wasmAssets);
multiAsset.insert(csl.ScriptHash.from_bytes(Buffer.from(policy, 'hex')), wasmAssets);
}
value.set_multiasset(multiAsset);
return value;
}
};
});
14 changes: 9 additions & 5 deletions packages/core/test/Ogmios/ogmiosToCsl.test.ts
@@ -1,4 +1,4 @@
import { CSL } from '@cardano-sdk/cardano-serialization-lib';
import { CardanoSerializationLib, CSL, loadCardanoSerializationLib } from '@cardano-sdk/cardano-serialization-lib';
import { ogmiosToCsl } from '../../src/Ogmios';
import * as OgmiosSchema from '@cardano-ogmios/schema';

Expand All @@ -10,16 +10,20 @@ const txOut: OgmiosSchema.TxOut = {
};

describe('ogmiosToCsl', () => {
let csl: CardanoSerializationLib;
beforeAll(async () => {
csl = await loadCardanoSerializationLib();
});
test('txIn', () => {
expect(ogmiosToCsl.txIn(txIn)).toBeInstanceOf(CSL.TransactionInput);
expect(ogmiosToCsl(csl).txIn(txIn)).toBeInstanceOf(CSL.TransactionInput);
});
test('txOut', () => {
expect(ogmiosToCsl.txOut(txOut)).toBeInstanceOf(CSL.TransactionOutput);
expect(ogmiosToCsl(csl).txOut(txOut)).toBeInstanceOf(CSL.TransactionOutput);
});
test('utxo', () => {
expect(ogmiosToCsl.utxo([[txIn, txOut]])[0]).toBeInstanceOf(CSL.TransactionUnspentOutput);
expect(ogmiosToCsl(csl).utxo([[txIn, txOut]])[0]).toBeInstanceOf(CSL.TransactionUnspentOutput);
});
test('value', () => {
expect(ogmiosToCsl.value(txOut.value)).toBeInstanceOf(CSL.Value);
expect(ogmiosToCsl(csl).value(txOut.value)).toBeInstanceOf(CSL.Value);
});
});
14 changes: 11 additions & 3 deletions packages/wallet/src/InMemoryUtxoRepository.ts
Expand Up @@ -3,18 +3,26 @@ import { UtxoRepository } from './UtxoRepository';
import { CardanoProvider, Ogmios } from '@cardano-sdk/core';
import { dummyLogger, Logger } from 'ts-log';
import { InputSelector, SelectionConstraints, SelectionResult } from '@cardano-sdk/cip2';
import { CSL } from '@cardano-sdk/cardano-serialization-lib';
import { CardanoSerializationLib, CSL } from '@cardano-sdk/cardano-serialization-lib';
import { KeyManager } from './KeyManagement';

export class InMemoryUtxoRepository implements UtxoRepository {
#csl: CardanoSerializationLib;
#delegationAndRewards: Schema.DelegationsAndRewards;
#inputSelector: InputSelector;
#keyManager: KeyManager;
#logger: Logger;
#provider: CardanoProvider;
#utxoSet: Set<[TxIn, TxOut]>;

constructor(provider: CardanoProvider, keyManager: KeyManager, inputSelector: InputSelector, logger?: Logger) {
constructor(
csl: CardanoSerializationLib,
provider: CardanoProvider,
keyManager: KeyManager,
inputSelector: InputSelector,
logger?: Logger
) {
this.#csl = csl;
this.#logger = logger ?? dummyLogger;
this.#provider = provider;
this.#utxoSet = new Set();
Expand Down Expand Up @@ -55,7 +63,7 @@ export class InMemoryUtxoRepository implements UtxoRepository {
await this.sync();
}
return this.#inputSelector.select({
utxo: Ogmios.ogmiosToCsl.utxo([...this.#utxoSet.values()]),
utxo: Ogmios.ogmiosToCsl(this.#csl).utxo([...this.#utxoSet.values()]),
outputs,
constraints
});
Expand Down
2 changes: 1 addition & 1 deletion packages/wallet/src/SingleAddressWallet.ts
Expand Up @@ -41,7 +41,7 @@ export const createSingleAddressWallet = async (
const validityInterval = ensureValidityInterval(tip.slot, props.options?.validityInterval);
const txOutputs = csl.TransactionOutputs.new();
for (const output of props.outputs) {
txOutputs.add(Ogmios.ogmiosToCsl.txOut(output));
txOutputs.add(Ogmios.ogmiosToCsl(csl).txOut(output));
}
const inputSelectionResult = await utxoRepository.selectInputs(txOutputs, {
computeMinimumCost: async ({ utxo, outputs, change }) => {
Expand Down
39 changes: 15 additions & 24 deletions packages/wallet/test/InMemoryUtxoRepository.test.ts
Expand Up @@ -10,35 +10,13 @@ import { NO_CONSTRAINTS } from './util';
const addresses = [
'addr_test1qq585l3hyxgj3nas2v3xymd23vvartfhceme6gv98aaeg9muzcjqw982pcftgx53fu5527z2cj2tkx2h8ux2vxsg475q2g7k3g'
];
// const stakeKeyHash = 'stake_test1up7pvfq8zn4quy45r2g572290p9vf99mr9tn7r9xrgy2l2qdsf58d';

// const txIn: OgmiosSchema.TxIn[] = [
// { txId: '0f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5', index: 0 },
// { txId: '08fc1f8af3abbc8fc1f8a466e6e754833a08a62a059bf059bf5483a8a66e6e74', index: 0 }
// ];

const outputs = CSL.TransactionOutputs.new();

outputs.add(
Ogmios.ogmiosToCsl.txOut({
address: addresses[0],
// value: { coins: 4_000_000, assets: { '2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740': 20n } }
value: { coins: 4_000_000 }
})
);
outputs.add(
Ogmios.ogmiosToCsl.txOut({
address: addresses[0],
// value: { coins: 2_000_000, assets: { '2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740': 20n } }
value: { coins: 2_000_000 }
})
);

describe('InMemoryUtxoRepository', () => {
let utxoRepository: UtxoRepository;
let provider: CardanoProvider;
let inputSelector: InputSelector;
let csl: CardanoSerializationLib;
let outputs: CSL.TransactionOutputs;

beforeEach(async () => {
provider = providerStub();
Expand All @@ -50,7 +28,20 @@ describe('InMemoryUtxoRepository', () => {
networkId: 0,
password: '123'
});
utxoRepository = new InMemoryUtxoRepository(provider, keyManager, inputSelector);
outputs = csl.TransactionOutputs.new();
outputs.add(
Ogmios.ogmiosToCsl(csl).txOut({
address: addresses[0],
value: { coins: 4_000_000 }
})
);
outputs.add(
Ogmios.ogmiosToCsl(csl).txOut({
address: addresses[0],
value: { coins: 2_000_000 }
})
);
utxoRepository = new InMemoryUtxoRepository(csl, provider, keyManager, inputSelector);
});

test('constructed state', async () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/wallet/test/SingleAddressWallet.test.ts
Expand Up @@ -27,7 +27,7 @@ describe('Wallet', () => {
});
provider = providerStub();
inputSelector = roundRobinRandomImprove(csl);
utxoRepository = new InMemoryUtxoRepository(provider, keyManager, inputSelector);
utxoRepository = new InMemoryUtxoRepository(csl, provider, keyManager, inputSelector);
});

test('createWallet', async () => {
Expand Down
34 changes: 16 additions & 18 deletions packages/wallet/test/createTransactionInternals.test.ts
Expand Up @@ -11,28 +11,12 @@ import { NO_CONSTRAINTS } from './util';
const address =
'addr_test1qq585l3hyxgj3nas2v3xymd23vvartfhceme6gv98aaeg9muzcjqw982pcftgx53fu5527z2cj2tkx2h8ux2vxsg475q2g7k3g';

const outputs = CSL.TransactionOutputs.new();

outputs.add(
Ogmios.ogmiosToCsl.txOut({
address,
// value: { coins: 4_000_000, assets: { '2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740': 20n } }
value: { coins: 4_000_000 }
})
);
outputs.add(
Ogmios.ogmiosToCsl.txOut({
address,
// value: { coins: 2_000_000, assets: { '2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740': 20n } }
value: { coins: 2_000_000 }
})
);

describe('createTransactionInternals', () => {
let csl: CardanoSerializationLib;
let provider: CardanoProvider;
let inputSelector: InputSelector;
let utxoRepository: UtxoRepository;
let outputs: CSL.TransactionOutputs;

beforeEach(async () => {
csl = await loadCardanoSerializationLib();
Expand All @@ -44,7 +28,21 @@ describe('createTransactionInternals', () => {
networkId: Cardano.NetworkId.testnet,
password: '123'
});
utxoRepository = new InMemoryUtxoRepository(provider, keyManager, inputSelector);
outputs = CSL.TransactionOutputs.new();

outputs.add(
Ogmios.ogmiosToCsl(csl).txOut({
address,
value: { coins: 4_000_000 }
})
);
outputs.add(
Ogmios.ogmiosToCsl(csl).txOut({
address,
value: { coins: 2_000_000 }
})
);
utxoRepository = new InMemoryUtxoRepository(csl, provider, keyManager, inputSelector);
});

test('simple transaction', async () => {
Expand Down

0 comments on commit e9a2421

Please sign in to comment.