Skip to content

Commit

Permalink
Merge pull request #69 from shareslake/5.0
Browse files Browse the repository at this point in the history
Update wrapper for Conway era
  • Loading branch information
miguelaeh authored May 26, 2024
2 parents f6809f9 + 195af7c commit b55623c
Show file tree
Hide file tree
Showing 32 changed files with 5,288 additions and 3,366 deletions.
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
node_modules
.env
package-lock.json
priv
583 changes: 0 additions & 583 deletions API.md

This file was deleted.

97 changes: 26 additions & 71 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,16 @@

## Overview

This is a library, which wraps the cardano-cli with JavaScript and makes it possible to interact with the cli-commands much faster and more efficient.
This is a library wrapping the cardano-cli with TypeScript (can also be used in Javascript projects) which makes it possible to interact with the cardano CLI much faster and more efficient.

#### This library was initially brought by [BerryPool](http://pipool.online/) and currently maintained by [Shareslake](https://www.shareslake.com). You can support the work by delegating to the Berry pool.
## Prerequisites

#### Donations (ADA):
You need access to a Cardano Node socket. If you have a remote node you can create a ssh tunnel with the socket file as follows:

- Shareslake:
```
addr1q9rsrh7kjhct7llm88dug6l5mh047gq6yq3wt3gjfd6uk3ldch4wp7w7v3ac4wp6q33gz2kemwn8ap6zch0u3za6pypshaa6ry
```
- Berry:
```
addr1q97x8rfnkw4pmdgnwjzavl8jvg77tuy6wn3wm90x9emwgj8nhh356yzp7k3qwmhe4fk0g5u6kx5ka4rz5qcq4j7mvh2sg67tj5
ssh -nNT -L /tmp/forwarded.socket:/path/to/remote/node.socket remote-machine-user@remote-machine-ip
```


## Prerequisites

- `cardano-node >= 1.29.0`
- `node.js >= 12.19.0`

## Install

#### NPM
Expand All @@ -34,7 +23,7 @@ npm install cardanocli-js
#### From source

```bash
git clone https://github.com/shareslake/cardanocli-js.git
git clone https://github.com/miguelaeh/cardanocli-js.git
cd cardanocli-js
npm install
```
Expand All @@ -48,75 +37,41 @@ const shelleyGenesisPath = "/home/ada/mainnet-shelley-genesis.json";
const cardanocliJs = new CardanocliJs({ shelleyGenesisPath });

const createWallet = (account) => {
const payment = cardanocliJs.addressKeyGen(account);
const stake = cardanocliJs.stakeAddressKeyGen(account);
cardanocliJs.stakeAddressBuild(account);
cardanocliJs.addressBuild(account, {
const payment = cardanocliJs.address.keyGen(account);
const stake = cardanocliJs.stake_address.keyGen(account);
cardanocliJs.stake_address.build(account);
const addr = cardanocliJs.address.build(account, {
paymentVkey: payment.vkey,
stakeVkey: stake.vkey,
});
return cardanocliJs.wallet(account);
return addr;
};

const createPool = (name) => {
cardanocliJs.nodeKeyGenKES(name);
cardanocliJs.nodeKeyGen(name);
cardanocliJs.nodeIssueOpCert(name);
cardanocliJs.nodeKeyGenVRF(name);
return cardanocliJs.pool(name);
};
const walletAddr = createWallet("my-wallet-name");

const wallet = createWallet("Ada");
const pool = createPool("Berry");

console.log(wallet.paymentAddr);
console.log(pool.vrf.vkey);
console.log("My wallet address:", walletAddr);
```

Check /examples for more use cases.

## API
Check `/examples` for more use cases. If you have doubts on how to use a specific command you can also check the `tests` folder, where all the commands are tested.

- <a href="./API.md">API Documentation</a>

## Structure

All files will be stored and used in the directory you choose when instantiating CardanocliJs (`dir`).
The directory is split in two subfolders `tmp` and `priv`.
In the `tmp` folder are stored protocol paramters, raw transactions, signed transactions and witnesses with unique identifiers.
The `priv` folder is again divided into two subolders holding on one site the pools `pool` and on the other side the wallets `wallet` (like [CNTools](https://cardano-community.github.io/guild-operators/#/) structure).
## Tests

Example structure:
Install npm dev dependencies using `npm install --also=dev`.

```
dir
tmp
<tx_1.raw>
...
priv
pool
Berry
<Berry.node.vkey>
<Berry.node.skey>
<Berry.vrf.vkey>
...
wallet
Lovelace
<Lovelace.payment.vkey>
<Lovelace.stake.skey>
...
```
Tests are using Jest framework and can be run by using `npm run-script test` command.

## Tests
Tests are configured to run with the Sancho network. You may need to update your `cardano-cli` binary to the sancho one in order to run the tests.

Install npm dev dependencies using `npm install --also=dev`.
## Major changes

Tests are using Jest framework and can be run by using `npm -s run test` command.
### 5.0.0

To configure the test suite, make a copy of `.env.dist` and rename it `.env`. Then change all parameters values to fit your environment.
Starting on version `4.0.0` the HTTP provider has been removed. There are better options for that as of today. For example, the blockfrost API.
This means than to use this library you need a fully synced node. And it is, as its name states, a wrapper over the CLI to make your life easier when creating scripts.
If you need to connect to your own remote cardano nodes you can forward the socket via an SSH tunnel:

**Caution**: The `TEST_WORKSPACE_DIR` will be deleted at the end of the test suite. **NEVER USE AN EXISTING DIRECTORY !!!** You may disable this behavior by commenting the cleanup function in `test/index.test.js`:
```
ssh -nNT -L /tmp/forwarded.socket:/path/to/remote/node.socket remote-machine-user@remote-machine-ip
```

afterAll(() => {
// cleanUpTestDirectory();
});
For better maintencane, the library has been moved to TypesScript and its internal structure changed.
58 changes: 0 additions & 58 deletions examples/deregisterWallet.js

This file was deleted.

112 changes: 60 additions & 52 deletions examples/mintMA.js
Original file line number Diff line number Diff line change
@@ -1,63 +1,71 @@
const CardanocliJs = require("../index.js");
const os = require("os");
const path = require("path");

const dir = path.join(os.homedir(), "testnet");
const shelleyPath = path.join(
os.homedir(),
"testnet",
"testnet-shelley-genesis.json"
);

const cardanocliJs = new CardanocliJs({
network: "testnet-magic 1097911063",
dir: dir,
shelleyGenesisPath: shelleyPath,
});
import CardanoCliJs from "../index";
import { CardanoCliJsOptions } from "../lib/cardanoclijs";
import fs from 'fs';

const createTransaction = (tx) => {
let raw = cardanocliJs.transactionBuildRaw(tx);
let fee = cardanocliJs.transactionCalculateMinFee({
...tx,
txBody: raw,
});
tx.txOut[0].value.lovelace -= fee;
return cardanocliJs.transactionBuildRaw({ ...tx, fee });
};
const options = new CardanoCliJsOptions({ shelleyGenesisPath: `${__dirname}/../tests/assets/shelley-genesis.json` });
const cli = new CardanoCliJs(options);

const signTransaction = (wallet, tx, script) => {
return cardanocliJs.transactionSign({
signingKeys: [wallet.payment.skey, wallet.payment.skey],
txBody: tx,
const createWallet = (account) => {
const payment = cardanocliJs.address.keyGen(account);
const stake = cardanocliJs.stake_address.keyGen(account);
cardanocliJs.stake_address.build(account);
const addr = cardanocliJs.address.build(account, {
paymentVkey: payment.vkey,
stakeVkey: stake.vkey,
});
return addr;
};

const wallet = cardanocliJs.wallet("Berry");
const walletName = "test-wallet";
const wallet = createWallet(walletName);
const mintScript = {
keyHash: cardanocliJs.addressKeyHash(wallet.name),
keyHash: cli.address.keyHash(walletName),
type: "sig",
};
const policy = cardanocliJs.transactionPolicyid(mintScript);
const scriptFile = fs.writeFileSync("/tmp/script.json", JSON.stringify(mintScript));
const policyId = cli.transaction.transactionPolicyId(scriptFile);
const realAssetName = "Berrycoin"
const assetName = Buffer.from(realAssetName).toString('hex')
const BERRYCOIN = policy + "." + assetName;

const tx = {
txIn: wallet.balance().utxo,
txOut: [
{
address: wallet.paymentAddr,
value: { ...wallet.balance().value, [BERRYCOIN]: 100 },
},
],
mint: [
{ action: "mint", quantity: 100, asset: BERRYCOIN, script: mintScript },
],
witnessCount: 2,
};
const BERRYCOIN = policyId + "." + assetName;

const addr = fs.readFileSync(`${cli.options.dir}/priv/wallet/${walletName}/${walletName}.payment.addr`, 'utf8');
const utxos = cli.query.utxo(addr);
const balance = utxos.forEach((utxo) => {
Object.keys(utxo.value).forEach((asset) => {
if (!value[asset]) value[asset] = 0;
value[asset] += utxo.value[asset];
});
});

// Create raw tx
const raw_opts = [];
for (let utxo of Object.keys(utxos)) {
raw_opts.push({ name: 'tx-in', value: utxo});
}
raw_opts.push({ name: 'tx-out', value: `${addr} ${balance}`});
// Mint 100 tokens
raw_opts.push({ name: 'mint', value: `100 ${BERRYCOIN}`});
raw_opts.push({ name: 'minting-script-file', value: scriptFile });
const draftTxFile = cli.transaction.buildRaw(raw_opts);
const fee = cli.transaction.calculateMinFee(draftTxFile, utxos.length, 1, 1);

// Create the options again with the correct amount (removing the fee)
const opts = [];
for (let utxo of Object.keys(utxos)) {
opts.push({ name: 'tx-in', value: utxo});
}
opts.push({ name: 'tx-out', value: `${addr} ${balance - fee}`});
// Mint 100 tokens
opts.push({ name: 'mint', value: `100 ${BERRYCOIN}`});
opts.push({ name: 'minting-script-file', value: scriptFile });
opts.push({ name: 'fee', value: fee });
const rawTxFile = cli.transaction.buildRaw(opts);

const signedTxFile = cli.transaction.sign(rawTxFile, [
`${cli.options.dir}/priv/wallet/${walletName}/${walletName}.payment.skey`
]);

console.log(cli.transaction.view({ txFile: signedTxFile }));

const raw = createTransaction(tx);
const signed = signTransaction(wallet, raw);
console.log(cardanocliJs.transactionView({ txFile: signed }));
const txHash = cardanocliJs.transactionSubmit(signed);
console.log(txHash);
// Submit the transaction to actually mint the asset
cli.transaction.submit(signedTxFile);
23 changes: 5 additions & 18 deletions examples/queryTip.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,7 @@
const CardanocliJs = require("../index.js");
const os = require("os");
const path = require("path");
import CardanoCliJs from "../index";
import { CardanoCliJsOptions } from "../lib/cardanoclijs";

const dir = path.join(os.homedir(), "testnet");
const shelleyPath = path.join(
os.homedir(),
"testnet",
"testnet-shelley-genesis.json"
);
const options = new CardanoCliJsOptions({ shelleyGenesisPath: `${__dirname}/../tests/assets/shelley-genesis.json` });
const cli = new CardanoCliJs(options);

const cardanocliJs = new CardanocliJs({
network: "testnet-magic 1097911063",
era: "alonzo",
dir: dir,
shelleyGenesisPath: shelleyPath,
socketPath: path.join(os.homedir(), "testnet", "db", "socket"),
});

console.log(cardanocliJs.queryTip());
console.log(cli.query.tip());
Loading

0 comments on commit b55623c

Please sign in to comment.