That is the third a part of cardano-client-lib collection. On this put up, I’ll clarify the right way to create a brand new Native Token utilizing Java. On this put up additionally, we might be utilizing Blockfrost backend api.
You’ll be able to verify Half I and Half II of this collection earlier than persevering with with this put up
- Cardano-client-lib: A Java Library to work together with Cardano -Half I
- Cardano-client-lib: Transaction with Metadata in Java- Half II
In Cardano, you’ll be able to mint a brand new native token with out writing a wise contract. Customers can transact with ada, and a limiteless variety of user-defined (customized) tokens natively.
Let’s create a brand new native token.
- Undertaking and account setup
If in case you have not setup your challenge but, please observe the step-1 to step-6 from Half I.
2. Create a Coverage Script & Coverage Id
In Cardano, token minting insurance policies are written utilizing multi-signature scripts. This permits the asset controller to precise situations equivalent to the necessity for particular token issuers to conform to mint new tokens, or to forbid minting tokens after a sure slot.
The library offers following courses to create several types of supported insurance policies :
- ScriptPubKey
- ScriptAll
- ScriptAny
- ScriptAtLeast
- RequireTimeAfter
- RequireTimeBefore
You’ll be able to construct a quite simple minting coverage, which grants the correct to mint tokens to a single key or construct a posh coverage by combining above courses.
On this put up, we’ll create a easy coverage, which grants the correct to mint tokens to a single key.
Let’s create a key-pair which we can be utilized to create the coverage.
Keys keys = KeyGenUtil.generateKey(); VerificationKey vkey = keys.getVkey(); SecretKey skey = keys.getSkey();
Create a ScriptPubKey, which grants the correct to mint tokens to the above generated key.
ScriptPubkey scriptPubkey = ScriptPubkey.create(vkey);
We are able to now generate coverage id from scriptPubKey object.
String policyId = scriptPubkey.getPolicyId();
3. Outline our new native token utilizing MultiAsset class
Create an occasion of MultiAsset class. Use the coverage id generated in earlier step. Create an asset object with a customized identify and token amount.
MultiAsset multiAsset = new MultiAsset(); multiAsset.setPolicyId(policyId); Asset asset = new Asset("TestCoin", BigInteger.valueOf(250000)); multiAsset.getAssets().add(asset);
4. Connect Metadata to Mint Token transaction (Optionally available)
If you wish to connect some metadata to this token mint transaction, you are able to do so utilizing Metadata apis supplied by the library.
CBORMetadataMap tokenInfoMap = new CBORMetadataMap() .put("token", "Check Token") .put("image", "TTOK"); CBORMetadataList tagList = new CBORMetadataList() .add("tag1") .add("tag2"); Metadata metadata = new CBORMetadata() .put(new BigInteger("770001"), tokenInfoMap) .put(new BigInteger("770002"), tagList);
5. Create Token Minting request
Create a token minting transaction request utilizing MintTransaction class.
MintTransaction mintTransaction = MintTransaction.builder() .sender(sender) .mintAssets(Arrays.asList(multiAsset)) .policyScript(scriptPubkey) .policyKeys(Arrays.asList(skey)) .construct();
Be aware: Aside from setting the multiAsset object created within the step-3, we’re additionally including our coverage script (scriptPubKey) and coverage secret key (skey) which had been generated in step-2.
In case you don’t set coverage script and coverage keys, the token mint transaction will fail.
If the receiver discipline isn’t set, the minted token might be allotted to the sender account.
6. Calculate TTL (Time To Dwell) and charge
Calculate TTL
lengthy ttl = blockService.getLastestBlock().getValue().getSlot() + 1000; TransactionDetailsParams detailsParams = TransactionDetailsParams.builder() .ttl(ttl) .construct();
Calculate charge and set the charge in mint transaction
BigInteger charge = feeCalculationService.calculateFee(mintTransaction, detailsParams, metadata); mintTransaction.setFee(charge);
7. Submit the Mint Token transaction
Lastly, submit the token mint transaction utilizing TransactionHelperService.
Outcomeend result = transactionHelperService.mintToken(mintTransaction, detailsParams, metadata); if(end result.isSuccessful()) System.out.println("Transaction Id: " + end result.getValue()); else System.out.println("Transaction failed: " + end result);
8. Examine transaction particulars in Cardano Explorer
Now go to Cardano Testnet Explorer and verify transaction particulars.
It might take a while for the transaction to be mined.
You must now see the minted token beneath the receiver’s tackle. (If no receiver is specified, beneath sender’s tackle)
9. Get particulars of our newly minted asset
First get asset id by combining beforehand generated coverage id after which the HEX encoded worth of our asset identify.
String policyId = "abe83f0124320fc4e6f50605e7986390453bcc0c913c920a249545eb"; String assetName = HexUtil.encodeHexString("TestCoin".getBytes(StandardCharsets.UTF_8)); String assetId = policyId + assetName;
Then use AssetService to get asset particulars.
Outcomeasset = assetService.getAsset(assetId); System.out.println(JsonUtil.getPrettyJson(asset.getValue()));
Output:
{ "policy_id" : "abe83f0124320fc4e6f50605e7986390453bcc0c913c920a249545eb", "asset_name" : "54657374436f696e", "fingerprint" : "asset1uw2v9tzrp6ntvzc48l28j2jc2r4k569hxxk463", "amount" : "4000", "initial_mint_tx_hash" : "d9da361f3e5237832cfcbdea16d440c9ea3e5026c7370c368291aafb5c2646a6" }
10. Create complicated insurance policies by combining completely different script courses
Within the under coverage script instance, we’re making a ScriptAll coverage by combining RequireTimeBefore and ScriptAtLeast script.
//Key 1 - Single Key Coverage Tupletuple1 = ScriptPubkey.createWithNewKey(); ScriptPubkey scriptPubkey1 = tuple1._1; SecretKey sk1 = tuple1._2.getSkey(); //Key 2 - Single Key Coverage Tuple tuple2 = ScriptPubkey.createWithNewKey(); ScriptPubkey scriptPubkey2 = tuple2._1; SecretKey sk2 = tuple2._2.getSkey(); //Key 3 - Single Key Coverage Tuple tuple3 = ScriptPubkey.createWithNewKey(); ScriptPubkey scriptPubkey3 = tuple3._1; SecretKey sk3 = tuple3._2.getSkey(); //AtLeast coverage with min-required key 2 ScriptAtLeast scriptAtLeast = new ScriptAtLeast(2) .addScript(scriptPubkey1) .addScript(scriptPubkey2) .addScript(scriptPubkey3); lengthy slot = getTtl(); RequireTimeBefore requireTimeBefore = new RequireTimeBefore(slot); //Create the ultimate ScriptAll coverage by combining RequireTimeBefore and ScriptAtLeast ScriptAll scriptAll = new ScriptAll() .addScript(requireTimeBefore) .addScript( scriptAtLeast );
You’ll be able to print the the JSON worth of Script object and retailer it in a file. The generated JSON object is suitable with cardano-cli command line instrument.
Full supply code:
public void mintToken() throws ApiException, AddressExcepion, CborSerializationException { BackendService backendService = BackendFactory.getBlockfrostBackendService(Constants.BLOCKFROST_TESTNET_URL, Fixed.BF_PROJECT_KEY); FeeCalculationService feeCalculationService = backendService.getFeeCalculationService(); TransactionHelperService transactionHelperService = backendService.getTransactionHelperService(); BlockService blockService = backendService.getBlockService(); String senderMnemonic = "equipment coloration frog trick converse make use of go well with kind bomb goddess jewel main spoil fade individual ineffective measure handle warfare cut back few scrub past period"; Account sender = new Account(Networks.testnet(), senderMnemonic); Keys keys = KeyGenUtil.generateKey(); VerificationKey vkey = keys.getVkey(); SecretKey skey = keys.getSkey(); ScriptPubkey scriptPubkey = ScriptPubkey.create(vkey); String policyId = scriptPubkey.getPolicyId(); MultiAsset multiAsset = new MultiAsset(); multiAsset.setPolicyId(policyId); Asset asset = new Asset("TestCoin", BigInteger.valueOf(50000)); multiAsset.getAssets().add(asset); CBORMetadataMap tokenInfoMap = new CBORMetadataMap() .put("token", "Check Token") .put("image", "TTOK"); CBORMetadataList tagList = new CBORMetadataList() .add("tag1") .add("tag2"); Metadata metadata = new CBORMetadata() .put(new BigInteger("770001"), tokenInfoMap) .put(new BigInteger("770002"), tagList); MintTransaction mintTransaction = MintTransaction.builder() .sender(sender) .mintAssets(Arrays.asList(multiAsset)) .policyScript(scriptPubkey) .policyKeys(Arrays.asList(skey)) .construct(); lengthy ttl = blockService.getLastestBlock().getValue().getSlot() + 1000; TransactionDetailsParams detailsParams = TransactionDetailsParams.builder() .ttl(ttl) .construct(); BigInteger charge = feeCalculationService.calculateFee(mintTransaction, detailsParams, metadata); mintTransaction.setFee(charge); Outcome<String<g; end result = transactionHelperService.mintToken(mintTransaction, detailsParams, metadata); if(end result.isSuccessful()) System.out.println("Transaction Id: " + end result.getValue()); else System.out.println("Transaction failed: " + end result); }