New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

cardano-pab-client

Package Overview
Dependencies
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cardano-pab-client

A set of tools to develop frontends that interact with the Plutus Application Backend.

  • 0.0.5
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

Cardano PAB client library

Instalation

npm i cardano-pab-client

Basic usage

It follows a simple use case of the entire flow for starting a contract: first getting the unbalanced transaction from a PAB, then balancing, signing and submitting it to the blockchain.

function startContract(): ContractEndpoints {
  // NOTE: all the modules of this library MUST be imported dynamically like this
  const {
    CIP30WalletWrapper,
    Balancer,
    getProtocolParamsFromBlockfrost,
  } = await import("cardano-pab-client");

  // initialize cip30 wallet
  // assuming we already have initialized the CIP30 wallet in the browser environment
  const wallet = await CIP30WalletWrapper.init(walletInjectedFromBrowser);

  // Initialize Balancer
  const protocolParams = await getProtocolParamsFromBlockfrost(
    "https://cardano-preprod.blockfrost.io/api/v0",
    "preprodXXXXXXXXXXXXXXXX",
  );
  const balancer = await Balancer.init(protocolParams);

  // Try to get unbalanced transaction from PAB
  const walletId = await wallet.getWalletId();
  const pabApi = new PABApi("http://localhost:9080");

  const [endpoints, pabResponse] = await ContractEndpoints.start(
    walletId,
    { endpointTag: "Init", params: [] },
    pabApi,
  );

  if (!succeeded(pabResponse)) {
    alert(
      `Didn't got the unbalanced transaction from the PAB. Error: ${pabResponse.error}`
    );
  } else {
    // the pab yielded the unbalanced transaction. balance, sign and submit it.
    const etx = pabResponse.value;

    const walletInfo = await wallet.getWalletInfo();
    const txBudgetApi = new TxBudgetAPI({
      baseUrl: "http//:localhost:3001",
      timeout: 10000,
    });

    const fullyBalancedTx = await balancer.fullBalanceTx(
      etx,
      walletInfo,
      // configuration for the balanceTx and rebalanceTx methods which are interally
      // used by this method
      { feeUpperBound: 1000000, mergeSignerOutputs: false },
      // a high-order function that exposes the balanced tx and the inputs info so to
      // calculate the executions units, which are then set in the transaction and
      // goes to the rebalancing step
      async (balancedTx, inputsInfo) => {
        const txBudgetResponse = await txBudgetApi.estimate(balancedTx, inputsInfo);
        if (succeeded(txBudgetResponse)) {
            const units = txBudgetResponse.value;
            return units;
        }
        // if the tx budget service fails or it isn't available,
        // fallback to hardcoded units

        // directly use the serialization library is useful here
        // must be dynamically imported too!
        const { SerLibLoader } = await import("cardano-pab-client");
        await SerLibLoader.load();
        const S = SerLibLoader.lib;

        // parse the transaction cbor into a nice format
        const tx = S.Transaction.from_hex(balancedTx).to_js_value();
        // ... here you have all the info of the transaction
        // in particular, access to the redeemers like so
        const { redeemers } = tx.witness_set;
        // also, have the complete information about the inputs (not only
        // the references) in the inputsInfo object

        if (redeemers) {
          redeemers.forEach((r: S.RedeemerJSON) => /*...*/);
          // do stuff...
          return [
            [{ tag: "Mint", index: 0 }, { mem: 4000000, cpu: 1500000000 }],
            [{ tag: "Spend", index: 2 }, { mem: 6000000, cpu: 1800000000 }],
            // ...
          ];
        }
        // no redeemers, so no hardcoded units are needed.
        return [];
      },
    );
    // print to the console the fully balanced tx cbor for debugging purposes
    console.log(`Balanced tx: ${fullyBalancedTx}`);
    // now that the transaction is balanced, sign and submit it with the wallet
    const response = await wallet.signAndSubmit(fullyBalancedTx);
    if (succeeded(response)) {
      const txHash = response.value;
      alert(`Start suceeded. Tx hash: ${txHash}`);
    } else {
      alert(`Start failed when trying to submit it. Error: ${response.error}`);
    }
  }
  // the ContractEndpoints instance is connected to the PAB, so we can return it to
  // continue doing operations with it.
  return endpoints;
}

For getting the CIP30 wallet from the user's browser, we have an utility that could be used within a React hook or something like it.

const {
  getWalletInitialAPI,
  CIP30WalletWrapper,
} = await import("cardano-pab-client");

const walletInitialAPI = getWalletInitialAPI(window, "eternl");
// or
// const walletInitialAPI = getWalletInitialAPI(window, "nami");

// this will ask the user to give to this dApp access to their wallet methods
const walletInjectedFromBrowser = await walletInitialAPI.enable();

// then we can initialize the CIP30WalletWrapper class of the library
const wallet = await CIP30WalletWrapper.init(walletInjectedFromBrowser);

// ...

Keywords

FAQs

Package last updated on 28 Dec 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc