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 {
const {
CIP30WalletWrapper,
Balancer,
getProtocolParamsFromBlockfrost,
} = await import("cardano-pab-client");
const wallet = await CIP30WalletWrapper.init(walletInjectedFromBrowser);
const protocolParams = await getProtocolParamsFromBlockfrost(
"https://cardano-preprod.blockfrost.io/api/v0",
"preprodXXXXXXXXXXXXXXXX",
);
const balancer = await Balancer.init(protocolParams);
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 {
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,
{ feeUpperBound: 1000000, mergeSignerOutputs: false },
async (balancedTx, inputsInfo) => {
const txBudgetResponse = await txBudgetApi.estimate(balancedTx, inputsInfo);
if (succeeded(txBudgetResponse)) {
const units = txBudgetResponse.value;
return units;
}
const { SerLibLoader } = await import("cardano-pab-client");
SerLibLoader.load();
const S = SerLibLoader.lib;
const tx = S.Transaction.from_hex(balancedTx).to_js_value();
const { redeemers } = tx.witness_set;
if (redeemers) {
redeemers.forEach((r: S.RedeemerJSON) => );
return [
[{ tag: "Mint", index: 0 }, { mem: 4000000, cpu: 1500000000 }],
[{ tag: "Spend", index: 2 }, { mem: 6000000, cpu: 1800000000 }],
];
}
return [];
},
);
console.log(`Balanced tx: ${fullyBalancedTx}`);
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}`);
}
}
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");
const walletInjectedFromBrowser = await walletInitialAPI.enable();
const wallet = await CIP30WalletWrapper.init(walletInjectedFromBrowser);