Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chore/update csl #43

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "cardano-metadata-oracle",
"version": "0.0.1-alpha",
"version": "0.0.2",
"author": "Five Binaries",
"bin": "./bin/run",
"bugs": "https://github.com/fivebinaries/cardano-metadata-oracle/issues",
Expand All @@ -11,8 +11,8 @@
"version": "oclif-dev readme && git add README.md"
},
"dependencies": {
"@blockfrost/blockfrost-js": "^1.1.0",
"@emurgo/cardano-serialization-lib-nodejs": "^8.0.0",
"@blockfrost/blockfrost-js": "^4.0.0",
"@emurgo/cardano-serialization-lib-nodejs": "^10.0.0-beta.8",
"@oclif/command": "^1.8.0",
"@oclif/config": "^1.17.0",
"@oclif/plugin-help": "^3.2.3",
Expand Down
5 changes: 5 additions & 0 deletions src/constants/params.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const CARDANO_PARAMS = {
COINS_PER_UTXO_WORD: '34482',
MAX_TX_SIZE: 16384,
MAX_VALUE_SIZE: 5000,
} as const;
12 changes: 2 additions & 10 deletions src/services/blockfrost/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,7 @@ export class BlockfrostClient implements BlockchainClient {
const response = await this.client.txSubmit(transaction);
return response;
} catch (err) {
if (err?.data) {
console.log(err?.data);
} else {
console.log(err);
}
console.log(err);
throw Error(ERROR.TRANSACTION_SUBMIT_FAIL);
}
};
Expand All @@ -40,11 +36,7 @@ export class BlockfrostClient implements BlockchainClient {
const response = await this.client.addressesUtxosAll(address);
return response;
} catch (err) {
if (err?.data) {
console.log(err?.data);
} else {
console.log(err);
}
console.log(err);
throw Error(ERROR.UTXOS_FETCH_FAIL);
}
};
Expand Down
20 changes: 10 additions & 10 deletions src/transaction/__tests__/__fixtures__/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,13 @@ export const signTransaction = [
txMetadata: {
ticker: [{ source: 'source_name', value: 'fugiat veniam minus' }],
},
result: '83a400818258208911f640d452c3be4ff3d89db63b41ce048c056951286e2e28bbf8a51588ab44000181825839009493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e32c728d3861e164cab28cb8f006448139c8f1740ffb8e7aa9e5232dc1a10b2531f021a00029519075820cb798b0bce50604eaf2e0dc89367896b18f0a6ef6b32b57e3c9f83f8ee71e608a1008182582073fea80d424276ad0978d4fe5310e8bc2d485f5f6bb3bf87612989f112ad5a7d5840c40425229749a9434763cf01b492057fd56d7091a6372eaa777a1c9b1ca508c914e6a4ee9c0d40fc10952ed668e9ad65378a28b149de6bd4204bd9f095b0a902a11907b0a1667469636b657281a266736f757263656b736f757263655f6e616d656576616c7565736675676961742076656e69616d206d696e7573',
result: '84a400818258208911f640d452c3be4ff3d89db63b41ce048c056951286e2e28bbf8a51588ab44000181825839009493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e32c728d3861e164cab28cb8f006448139c8f1740ffb8e7aa9e5232dc1a10b2531f021a00029519075820cb798b0bce50604eaf2e0dc89367896b18f0a6ef6b32b57e3c9f83f8ee71e608a1008182582073fea80d424276ad0978d4fe5310e8bc2d485f5f6bb3bf87612989f112ad5a7d5840c40425229749a9434763cf01b492057fd56d7091a6372eaa777a1c9b1ca508c914e6a4ee9c0d40fc10952ed668e9ad65378a28b149de6bd4204bd9f095b0a902f5a11907b0a1667469636b657281a266736f757263656b736f757263655f6e616d656576616c7565736675676961742076656e69616d206d696e7573',
},
];

export const composeTransaction = [
{
description: 'composeTransaction',
description: 'composeTransaction 1',
address:
'addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3jcu5d8ps7zex2k2xt3uqxgjqnnj83ws8lhrn648jjxtwq2ytjqp',
utxos: [
Expand All @@ -83,16 +83,16 @@ export const composeTransaction = [
},
],
result: {
outputAmount: '1824379',
totalFeesAmount: '175621',
outputAmount: '1824335',
totalFeesAmount: '175665',
usedUtxos: [
{
amount: [{ quantity: '1000000', unit: 'lovelace' }],
block: 'd42e18d2980f62474379c2b40d00e78825a00e6a788978e20ab14170531f1703',
output_index: 0,
tx_hash:
'c2d3af74aed2ff310890c2b54fce15ac42127959036ebc8261154fb4c0c9e0a1',
tx_index: 0,
output_index: 0,
amount: [{ unit: 'lovelace', quantity: '1000000' }],
block: 'd42e18d2980f62474379c2b40d00e78825a00e6a788978e20ab14170531f1703',
},
{
amount: [{ quantity: '1000000', unit: 'lovelace' }],
Expand All @@ -106,7 +106,7 @@ export const composeTransaction = [
},
},
{
description: 'composeTransaction',
description: 'composeTransaction 2',
address:
'addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3jcu5d8ps7zex2k2xt3uqxgjqnnj83ws8lhrn648jjxtwq2ytjqp',
utxos: [
Expand All @@ -120,8 +120,8 @@ export const composeTransaction = [
},
],
result: {
outputAmount: '9825963',
totalFeesAmount: '174037',
outputAmount: '9825919',
totalFeesAmount: '174081',
usedUtxos: [
{
tx_hash:
Expand Down
10 changes: 7 additions & 3 deletions src/transaction/__tests__/composeTransaction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,13 @@ describe('utils - composeTransaction', () => {
const tx = utils.composeTransaction(f.address, metadata, f.utxos);

// output amount
expect(tx.txBody.outputs().get(0).amount().coin().to_str()).toBe(
f.result.outputAmount,
);
if (tx.txBody.outputs().len() > 0) {
expect(
tx.txBody.outputs().get(0).amount().coin().to_str(),
).toBe(f.result.outputAmount);
} else {
expect(f.result.outputAmount).toBe('0');
}
expect(tx.info.outputAmount.to_str()).toBe(f.result.outputAmount);

// fee amount
Expand Down
127 changes: 78 additions & 49 deletions src/transaction/composeTransaction.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as CardanoWasm from '@emurgo/cardano-serialization-lib-nodejs';
import { sortUtxos } from '../utils/transaction';
import { bigNumFromStr, getAssetAmount, sortUtxos } from '../utils/transaction';
import { UTXO } from '../types';
import { CARDANO_PARAMS } from '../constants/params';

export const composeTransaction = (
address: string,
Expand All @@ -20,46 +21,49 @@ export const composeTransaction = (
if (!utxos || utxos.length === 0) {
throw 'No UTXOs to include in the transaction.';
}

const minUtxoValue = CardanoWasm.BigNum.from_str('1000000');
const txBuilder = CardanoWasm.TransactionBuilder.new(
CardanoWasm.LinearFee.new(
CardanoWasm.BigNum.from_str('44'),
CardanoWasm.BigNum.from_str('155381'),
),
minUtxoValue,
// pool deposit
CardanoWasm.BigNum.from_str('500000000'),
// key deposit
CardanoWasm.BigNum.from_str('2000000'),
CardanoWasm.TransactionBuilderConfigBuilder.new()
.fee_algo(
CardanoWasm.LinearFee.new(
bigNumFromStr('44'),
bigNumFromStr('155381'),
),
)
.pool_deposit(bigNumFromStr('500000000'))
.key_deposit(bigNumFromStr('2000000'))
.coins_per_utxo_word(
bigNumFromStr(CARDANO_PARAMS.COINS_PER_UTXO_WORD),
)
.max_value_size(CARDANO_PARAMS.MAX_VALUE_SIZE)
.max_tx_size(CARDANO_PARAMS.MAX_TX_SIZE)
.build(),
);

const outputAddr = CardanoWasm.Address.from_bech32(address);

let utxosTotalAmount = CardanoWasm.BigNum.from_str('0');
let totalFeesAmount = CardanoWasm.BigNum.from_str('0');

// set metadata
// Set metadata
const txMetadata = CardanoWasm.AuxiliaryData.from_bytes(
metadatum.to_bytes(),
);
txBuilder.set_auxiliary_data(txMetadata);
totalFeesAmount = txBuilder.min_fee();

const testOutput = CardanoWasm.TransactionOutput.new(
// Dummy output for calculating needed fee for a change output
const dummyOutput = CardanoWasm.TransactionOutput.new(
outputAddr,
CardanoWasm.Value.new(minUtxoValue),
CardanoWasm.Value.new(bigNumFromStr('1000000')),
);
const outputFee = txBuilder.fee_for_output(testOutput);
totalFeesAmount = totalFeesAmount.checked_add(outputFee);
const dummyOutputFee = txBuilder.fee_for_output(dummyOutput);

// add inputs
const usedUtxos = [];
const lovelaceUtxos = utxos.filter(
u => !u.amount.find(a => a.unit !== 'lovelace'),
);
const sortedUtxos = sortUtxos(lovelaceUtxos);
const usedUtxos = [];
for (const utxo of sortedUtxos) {
const amount = utxo.amount.find(a => a.unit === 'lovelace')?.quantity;
const sorted = sortUtxos(lovelaceUtxos);
let utxosTotalAmount = bigNumFromStr('0');
const cUtxo = CardanoWasm.TransactionUnspentOutputs.new();
for (const utxo of sorted) {
const amount = getAssetAmount(utxo);
if (!amount) continue;

const input = CardanoWasm.TransactionInput.new(
Expand All @@ -68,47 +72,72 @@ export const composeTransaction = (
),
utxo.output_index,
);

const inputValue = CardanoWasm.Value.new(
CardanoWasm.BigNum.from_str(amount.toString()),
const inputValue = CardanoWasm.Value.new(bigNumFromStr(amount));
const singleUtxo = CardanoWasm.TransactionUnspentOutput.new(
input,
CardanoWasm.TransactionOutput.new(outputAddr, inputValue),
);

const inputFee = txBuilder.fee_for_input(outputAddr, input, inputValue);
cUtxo.add(singleUtxo);
txBuilder.add_input(outputAddr, input, inputValue);

totalFeesAmount = totalFeesAmount.checked_add(inputFee);
utxosTotalAmount = utxosTotalAmount.checked_add(
CardanoWasm.BigNum.from_str(amount.toString()),
);
utxosTotalAmount = utxosTotalAmount.checked_add(bigNumFromStr(amount));
usedUtxos.push(utxo);

const fee = txBuilder.min_fee();
if (
utxosTotalAmount.compare(
totalFeesAmount.checked_add(minUtxoValue),
bigNumFromStr('1000000')
.checked_add(fee)
.checked_add(dummyOutputFee),
) >= 0
) {
// we have enough utxos to cover fee + minUtxoOutput
// enough utxo to cover change output
break;
}
}

const outputAmount = utxosTotalAmount.checked_sub(totalFeesAmount);
// add output to the tx
txBuilder.add_output(
CardanoWasm.TransactionOutput.new(
outputAddr,
CardanoWasm.Value.new(outputAmount),
),
);

txBuilder.set_fee(totalFeesAmount);
// Coin selection and change output
// Would be nice to use coinselection from CSL, but if there is an input with 1 ADA it will burn it all for fee
// instead of adding another input and returning change output
// txBuilder.add_inputs_from(
// cUtxo,
// CardanoWasm.CoinSelectionStrategyCIP2.LargestFirst,
// );
txBuilder.add_change_if_needed(outputAddr);

// once the transaction is ready, we build it to get the tx body without witnesses
// Build tx
const txBody = txBuilder.build();
const txId = Buffer.from(
CardanoWasm.hash_transaction(txBody).to_bytes(),
).toString('hex');

// Derive few unnecessary fields that are at least used in tests
const totalFeesAmount = txBody.fee();
let outputAmount = bigNumFromStr('0');

// Fill usedUtxos from txBody.inputs()
// const usedUtxos = [];
// let utxosTotalAmount = bigNumFromStr('0');
// for (let i = 0; i < txBody.inputs().len(); i++) {
// const utxo = txBody.inputs().get(i);
// const originalUtxo = utxos.find(
// u =>
// u.tx_hash ===
// Buffer.from(utxo.transaction_id().to_bytes()).toString(
// 'hex',
// ) && u.output_index === utxo.index(),
// );
// if (originalUtxo) {
// usedUtxos.push(originalUtxo);
// utxosTotalAmount = utxosTotalAmount.checked_add(
// bigNumFromStr(getAssetAmount(originalUtxo)),
// );
// }
// }

for (let i = 0; i < txBody.outputs().len(); i++) {
const output = txBody.outputs().get(i);
outputAmount = outputAmount.checked_add(output.amount().coin());
}

return {
txId,
txBody,
Expand Down
25 changes: 13 additions & 12 deletions src/utils/transaction.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,27 @@
import * as CardanoWasm from '@emurgo/cardano-serialization-lib-nodejs';
import { UTXO } from '../types';

export const bigNumFromStr = (num: string): CardanoWasm.BigNum =>
CardanoWasm.BigNum.from_str(num);

export const getAssetAmount = (
obj: Pick<UTXO, 'amount'>,
asset = 'lovelace',
): string => obj.amount.find(a => a.unit === asset)?.quantity ?? '0';

export const sortUtxos = (utxos: UTXO[]): UTXO[] => {
// smallest first
return utxos.sort((a, b) => {
const amountA = CardanoWasm.BigNum.from_str(
a.amount.find(a => a.unit === 'lovelace')?.quantity ?? '0',
);
const amountB = CardanoWasm.BigNum.from_str(
b.amount.find(a => a.unit === 'lovelace')?.quantity ?? '0',
);
const amountA = bigNumFromStr(getAssetAmount(a));
const amountB = bigNumFromStr(getAssetAmount(b));
return amountA.compare(amountB);
});
};

export const getRemainingBalance = (utxos: UTXO[]): string => {
let balance = CardanoWasm.BigNum.from_str('0');
let balance = bigNumFromStr('0');
utxos.forEach(u => {
balance = balance.checked_add(
CardanoWasm.BigNum.from_str(
u.amount.find(a => a.unit === 'lovelace')?.quantity ?? '0',
),
);
balance = balance.checked_add(bigNumFromStr(getAssetAmount(u)));
});
return balance.to_str();
};
Loading