Tutorial

Simple Boolean Policies: Maximum Units

This example will cover the use of the set_max_units boolean policy rule


const PASSWORD = 'findorarocks123';
const keyStore = new KeyStore.KeyStore(PASSWORD);
const masterKey = keyStore.genMasterKey(PASSWORD);
const aliceKeyPair = keyStore.genKeyPair(masterKey, 'Alice');
const network = new Network.Network(PROTOCOL, HOST, QUERY_PORT, SUBMISSION_PORT, LEDGER_PORT);

console.log('Key for Alice created.');

const tokenCode = Ledger.random_asset_type();
const memo = 'this is a test asset';
const assetRules = Ledger.AssetRules.new().set_max_units(BigInt(5));
let blockCount = BigInt((await network.getStateCommitment())[1]);
const definitionTransaction = Ledger.TransactionBuilder
  .new(blockCount).add_operation_create_asset(aliceKeyPair, memo, tokenCode, assetRules).transaction();

await network.submitTransaction(definitionTransaction);

console.log('Asset created.');

await Utils.sleep(4);
blockCount = BigInt((await network.getStateCommitment())[1]);
const zeiParams = Ledger.PublicParams.new(); // Cryptography public parameters necessary for creating asset records
const seqID = BigInt(await network.getIssuanceNum(tokenCode)); // To prevent operation replays, each ```IssueAsset``` operation must include a unique and increasing issuance number.
const amount = BigInt(10); // Amount of the asset to issue.
const confidential = false; // Whether the amount field of the asset record should be encrypted. Advanced features like confidentiality will be covered in a later example.

The IssueAsset operation below will, if accepted by the ledger, create a new asset record owned by Alice with 10 units of the asset she has just created. Since, by policy, she may create no more than 5 units, the transaction will be rejected.

console.log('Creating issuance transaction...');
const issueTxn = Ledger.TransactionBuilder.new(blockCount)
  .add_basic_issue_asset(aliceKeyPair, tokenCode, seqID, amount, confidential, zeiParams).transaction();

Alice will now attempt to submit her transaction.

console.log('Submitting transaction...');
const handle = await network.submitTransaction(issueTxn);
console.log(`Transaction submitted successfully! The transaction handle is ${handle}.`);

console.log('Getting transaction status...');
const transactionStatus = await network.getTxnStatus(handle);
console.log(JSON.stringify(transactionStatus));
if (transactionStatus.Rejected) {
  console.log('Your transaction was rejected');
  // throw "You probably violated a policy!";
} else if (transactionStatus.Committed) {
  console.log('All good');
} else { // if (transactionStatus["Pending"])
  console.log('Still waiting for your transaction to complete...');
}