Skip to content

Examples

Hai Eng edited this page Jan 6, 2022 · 16 revisions

Type of Requests

Get Transactions Info

TransactionHttp allows caller to announce signed transactions to the network via method announce. This is how all transactions are submitted.

  • Get transaction information by Transaction ID or Hash
  • Get transaction information by Transaction ID or Hash and Group
  • Get transactions information by Group
  • Get transactions information by Transaction IDs or hashes and Groups
  • Get transaction status by Transaction Hash or ID
  • Get transactions statuses by Transactions Hashes or IDs
  • Search transactions by query params

See TransactionHttpTest or any other test that submits requests to change something.

Get Accounts Info

AccountHttp allows caller to query for

  • Get account information for an account
  • Get account information for multiple accounts
  • Get account names for multiple accounts.
  • Get account properties for an account.
  • Get account properties for multiple accounts.
  • Get confirmed transactions information.
  • Get incoming transactions information.
  • Get outgoing transactions information.
  • Get partial transactions information.
  • Get unconfirmed transactions information.
  • Get multisig account information.
  • Get multisig account graph information.

See AccountHttpTest

Get Blockchain Info

BlockchainHttp allows caller to query for

  • get block information by block height.
  • get block transactions by block height.
  • get block information by block height.
  • get block receipts by block height.
  • get block storage information.
  • get receipt merkle path by block height and receipt hash.
  • get transaction merkle path by block height and transaction hash.
  • get block height with limit by block height and block limit.

See BlockchainHttpTest

Get Exchange Info

ExchangeHttp allows caller to query for

  • Get account exchanges from address
  • Get exchange offers by offer type and mosaic ID
  • Get exchange offer list

See ExchangeHttpTest

Get Metadata Info

Metadata allow tagging of Accounts, Mosaics and Namespaces with a key-value pairs of data. This can be used for purposes like blacklisting.

MetadataHttp allows caller to query for metadata associated with account, mosaic or namespace

  • Get metadata information by composite hash
  • Get metadata information by list of composite hash
  • Search metadata information by query params

See MetadataHttpTest

Get Mosaics Info

Mosaics represent tokens on the network.

MosaicHttp allows caller to query for

  • Get mosaic information by mosaic ID
  • Get mosaic information by list of mosaic ID
  • Get mosaic names defined as aliases for the mosaic
  • Get mosaic levy information by mosaic ID
  • Get mosaic rich list by mosaic ID

See MosaicHttpTest

Get Namespaces Info

Namespaces are similar to domain names. Root namespace (similar to top-level domain) can be declared with several sub-namespaces.

NamespaceHttp allow caller to query for namespace information. Namespaces are used to create aliases to mosaics and accounts.

  • Get namespace information by namespace Id
  • Get namespaces an account owns
  • Get readable names for a set of namespaces
  • Get namespace information by list of addresses

See NamespaceHttpTest

Get Network Info

NetworkHttp allow caller to query for

  • Get network type info

See NetworkHttpTest

Get Lock Info

Secret Lock and Proof allow exchange of secret between parties. This can be used for cross-chain swaps.

  • Get account lock hash by address or public key
  • Get account lock secret by address or public Key
  • Get composite hash by composite hash
  • Get lock hash by hash
  • Get secret hash by hash

See LockHttpTest

Transaction

Transaction builders are created by a factory retrieved by BlockchainApi#transact() call. Factory provides means to initialize defaults for transaction attributes which usually are used with default values

  • transaction deadline millis - no default. Specifies number of milliseconds after builder build() method invocation as a transaction deadline
  • network type - default retrieved from BlockchainApi. Network type is constant for used network
  • fee calculation strategy - default is MEDIUM. Fee calculation strategy defines cost of a byte of transaction

Following are examples of use of transaction builders. Paragraph title matches method name on the TransactionBuilderFactory represented as transact object which is initialized for default deadline.

// retrieve builder factory from BlockchainApi
TransactionRepository transact = api.transact();
// set default transaction deadline
transact.setDeadlineMillis(DEFAULT_DEADLINE_DURATION);
// in our examples we will b setting ZERO fee calcuation strategy - i.e. no fees
transact.setFeeCalculationStrategy(FeeCalculationStrategy.ZERO);

Many of the builders offer convenience methods which simplify use and to some extent provide checked API for builder use. It is possible to combine the use of convenience methods and standard setters (i.e. lock funds for aggregate and then change the mosaic). Always check JavaDoc for given builder when using it.

Account Link

AccountLinkTransaction unlink = transact.accountLink().unlink(publicAccount).build();
AccountLinkTransaction link = transact.accountLink().link(publicAccount).build();

See E2EAccountLinkTest

Account Properties

Account properties (or account restrictions) provide means to allow or block specified addresses, entity (transaction) types or mosaics.

Account Property Address

      // add address to list of blocked addresses
      ModifyAccountPropertyTransaction<Address> trans = transact.accountPropAddress()
            .blocked(Arrays.asList(AccountPropertyModification.add(blocked.getAddress())))
            .build();

Account Property Mosaic

      // add mosaic to allowed. NOTE this blacklists everything else
      ModifyAccountPropertyTransaction<UInt64Id> trans = transact.accountPropMosaic()
            .allowed(Arrays.asList(AccountPropertyModification.add(allowedMosaic))).build();

Account Property Entity Type

      // add entity type to allowed. NOTE this blacklists everything else
      ModifyAccountPropertyTransaction<EntityType> trans = transact.accountPropEntityType()
            .allowed(Arrays.asList(AccountPropertyModification.add(allowedTransType))).build();

See E2EAccountTest

Aggregate transactions

AggregateComplete

Aggregate complete transaction allows several inner transactions to be announced as single transaction to the network. Aggregate complete transaction requires all co-signatures to be available at the time of announcement to the network. It is not required to lock funds prior to the announcement.

      // wrap aliceToBob and bobToAlice to aggregate transaction. Both will need to cosign the aggregate transaction before announcement
      AggregateTransaction escrow = transact.aggregateComplete()
            .innerTransactions(aliceToBob.toAggregate(alice.getPublicAccount()),
                  bobToAlice.toAggregate(bob.getPublicAccount()))
            .build();

Aggregate Bonded

Aggregate bonded transaction allows several inner transactions to be announced as single transaction to the network. Aggregate bonded transaction assumes that cosignatories will provide their co-signatures after transaction announcement. It is required to lock funds for this transaction before transaction announcement.

      AggregateTransaction escrow = transact.aggregateBonded()
            .innerTransactions(aliceToBob.toAggregate(alice.getPublicAccount()),
                  bobToAlice.toAggregate(bob.getPublicAccount()))
            .build();

Inner transactions

Inner transactions require signer to be specified (that identifies for example which account is the transfer made from). This can be done either via toAggregate method call as shown in examples above or you can use transaction builders and specify signer directly when transaction is instantiated.

      TransactionBuilderFactory fac = api.transact();

      AggregateTransaction aggregateTx = fac.aggregateComplete().innerTransactions(
            // set signer directly
            fac.transfer().mosaics(amount).to(alice).signer(bob).build(),
            // use toAggregate
            fac.transfer().mosaics(amount).to(bob).signer(alice).build()
          ).build();

See E2EAggregateTest

Alias Transactions

Namespace can be used instead of address or mosaic when there is alias defined accordingly.

Alias Address

      // create alias for account address using accNamespaceId
      AliasTransaction alias = transact.aliasAddress().link(account.getAddress()).namespaceId(accNamespaceId).build();

Alias Mosaic

      // create alias for mosaicId using mosaNamespaceId
      AliasTransaction alias = transact.aliasMosaic().link(mosaicId).namespaceId(mosaNamespaceId).build();

See E2EAliasTest

Blockchain Config

Blockchain configuration can be changed when signed by the nemesis account.

      // prepare transaction
      BlockchainConfigTransaction trans = transact.blockchainConfig().applyHeightDelta(BigInteger.valueOf(3))
            .blockchainConfig(conf).supportedEntityVersions(entities).build();

See E2EBlockchainTest

Blockchain Upgrade

Blockchain upgrade defines which node version can participate in harvesting.

      BlockchainUpgradeTransaction trans = transact.blockchainUpgrade().upgradePeriod(upgradePeriod).newVersion(version)
            .build();

See E2EBlockchainTest

Exchange transactions

Exchange functionality is based on adding offer and then other people making offers to fulfill the standing offer. it is also possible to remove the offer.

NOTICE that amount and cost are specified in the absolute values (e.g. 1 token with divisibility 6 is represented as 1_000_000)

Exchange Add

         // try to purchase 1000 of EXCHANGED_MOSAIC_ID for 500 XPX
         AddExchangeOffer addOffer = new AddExchangeOffer(EXCHANGED_MOSAIC_ID, BigInteger.valueOf(1000),
               BigInteger.valueOf(500), ExchangeOfferType.BUY, BigInteger.valueOf(1000));
         ExchangeOfferAddTransaction addTrans = transact.exchangeAdd().offers(addOffer).build();

Exchange Offer

         // offer for 500 of EXCHANGED_MOSAIC_ID does not fulfill the standing offer
         ExchangeOffer offer = new ExchangeOffer(EXCHANGED_MOSAIC_ID, BigInteger.valueOf(500),
               BigInteger.valueOf(250), ExchangeOfferType.BUY, simpleAccount.getPublicAccount());
         ExchangeOfferTransaction offerTrans = transact.exchangeOffer().offers(offer).build();

Exchange Remove

         // remove the offer
         RemoveExchangeOffer removeOffer = new RemoveExchangeOffer(EXCHANGED_MOSAIC_ID, ExchangeOfferType.BUY);
         ExchangeOfferRemoveTransaction removeTrans = transact.exchangeRemove().offers(removeOffer).build();

See E2EExchangeTest

Lock Funds

Lock funds is mandatory for aggregate bonded transaction. Example below uses convenience method forAggregate which locks 10 network currency for specified signedTransaction for aggregate transaction.

      LockFundsTransaction lock = transact.lockFunds()
            .forAggregate(BigInteger.valueOf(480), signedTransaction).build();

When non-default network currency is used then specify the mosaic factory for the network currency

      LockFundsTransaction lock = transact.lockFunds()
            .forAggregate(NetworkCurrencyMosaic.FACTORY, BigInteger.valueOf(480), signedTransaction).build();

It is also possible to manually define the lock

      LockFundsTransaction lock = transact.lockFunds().mosaic(NetworkCurrencyMosaic.TEN)
            .duration(BigInteger.valueOf(480)).signedTransaction(signedTransaction).build();

Modify Metadata

Metadata can be attached to mosaics, namespaces and account.

Account Metadata

      // old value will be leave empty if the metadata was newly initialized 
      // modify account metadata
     AccountMetadataTransaction accountMetadataTransaction = transact.accountMetadata()
            .create(seedAccount.getPublicAccount(), test_name, test_value, "")
            .build();

Mosaic Metadata

      // modify namespace metadata
      MosaicMetadataTransaction mosaicMetadataTransaction = transact.mosaicMetadata()
            .create(seedAccount.getPublicAccount(), mosaicDefinition.getMosaicId(), test_name, test_value, "")
            .build();

Namespace Metadata

      // modify namespace metadata
     NamespaceMetadataTransaction namespaceMetadataTransaction = transact.namespaceMetadata()
            .create(seedAccount.getPublicAccount(),registerNamespaceTransaction.getNamespaceId(), test_name, test_value, "")
            .build();

See E2EMetadataTest

Mosaic Levy

Create or modify levy of a mosaic

Modify Mosaic Levy

     ModifyMosaicLevyTransaction mosaicLevyTransaction = transact.modifyMosaicLevy()
            .create(levy, mosaicDefinition.getMosaicId())
            .build();

Remove Mosaic Levy

     RemoveMosaicLevyTransaction removeMosaicLevyTransaction = transact.removeMosaicLevy()
            .create(mosaicId)
            .build();

Mosaic Definition

Create transaction to create new mosaic.

      // use convenience init method to make sure all information was provided
      MosaicDefinitionTransaction trans = transact.mosaicDefinition()
            .init(nonce, id, new MosaicProperties(true, true, 6, Optional.of(BigInteger.valueOf(20))))
            .build()

Mosaic Supply Change

Change supply of a mosaic. Use convenicence methods increase and decrease

      // increase supply change by 10. Using convenience method increase
      MosaicSupplyChangeTransaction increaseSupply = transact.mosaicSupplyChange()
            .increase(mosaicId, BigInteger.TEN)
            .build()
      // decrease supply change by 10. Using convenience method decrease
      MosaicSupplyChangeTransaction decreaseSupply = transact.mosaicSupplyChange()
            .decrease(mosaicId, BigInteger.TEN)
            .build()

See E2EMosaicTest

Multisig Modification

      // add 1 required approval for transactions
      ModifyMultisigAccountTransaction changeTo2of2 = transact.multisigModification().minApprovalDelta(1).build();
      // add cosig3 account as cosignatory
      ModifyMultisigAccountTransaction addCosig3 = transact.multisigModification()
            .modifications(MultisigCosignatoryModification.add(cosig3.getPublicAccount())).build();
      // make several changes to multisig account
      ModifyMultisigAccountTransaction changeToMultisig = transact.multisigModification()
            // increase minimum cosignatories for transaction approval by 1
            .minApprovalDelta(1)
            // increase minimum cosignatures for cosignatory removal by 1
            .minRemovalDelta(1)
            // add 2 cosignatories to the account
            .modifications(
                  MultisigCosignatoryModification.add(cosig1.getPublicAccount()),
                  MultisigCosignatoryModification.add(multisigAccount.getPublicAccount()))
            .build();

See E2EMultisigTest

Register Namespace

Transaction to register new namespace. Namespaces are either root or sub-namespaces creating hierarchy. Root namespace requires duration to be specified. Sub-namespaces are valid as long as root namespace is valid.

      // create new namespace with namespaceName as name and validity duration of 100 blocks
      RegisterNamespaceTransaction registerNamespaceTransaction = transact.registerNamespace()
            .rootNamespace(rootName)
            .duration(BigInteger.valueOf(100))
            .build();
      // create new sub-namespace for parent namespace parentNsId with name childName
      RegisterNamespaceTransaction registerNamespaceTransaction = transact.registerNamespace()
            .subNamespace(parentNsId, childName)
            .build();

See E2ENamespaceTest

Secret Hash

Secret lock and secret proof are typically used for cross-chain swaps. Cross-chain swap is realized by 2 lock-proof pairs. Be careful to set up lock durations so that both parties have time to provide proofs.

Secret Lock

      // lock funds as specified
      SecretLockTransaction secretLocktx = transact.secretLock()
            // lock 10 network currency
            .mosaic(NetworkCurrencyMosaic.ONE)
            // lock will expire after 10 blocks
            .duration(BigInteger.valueOf(10))
            // lock can be released by secret that has given hash
            .secret(hashType, secretHash)
            // locked funds will be transferred to specified address
            .recipient(recipientAddress)
            .build();
      // release locked funds to recipient by providing the proof

Secret Proof

      SecretProofTransaction secretProoftx = transact.secretProof()
            .secret(hashType, secretHash)
            .proof(secret)
            .recipient(Recipient.from(recipientAddress))
            .build();

See E2ESecretTest

Transfer

Transfer transaction can deliver specified amount of mosaic and message to recipient account. Message can be plain-text or secure. Secure message can be decoded only with knowledge of recipient's private key.

Transfer mosaic and/or a message (see below details for plain-text and secure message) to recipient account.

      TransferTransaction transfer = transact.transfer().mosaics(amount).to(recipient).message(message).build();

Plaintext message

     PlainMessage message = new PlainMessage("java SDK plain message test");

Secure message

Secure message is encrypted by private key of sender and public key of recipient

      SecureMessage message = SecureMessage.create(senderAccount.getKeyPair().getPrivateKey(),
            recipientAccount.getKeyPair().getPublicKey(),
            "java SDK secure message");

See E2ETransferTest

Copyright (c) 2022 ProximaX Limited