[Guides] Add dynamic generationHash and networkType
Originally reported here https://github.com/nemtech/nem2-docs/pull/323#issuecomment-573319429 by @fboucquez
RepositoryFactory knows how to load and cache
networkTypeandgenerationHash. What about doing something like this:const sendintATransferTransaction = async () => { /* Start block 00*/ const nodeUrl = 'http://api-harvest-20.us-west-1.nemtech.network:3000'; const repositoryFactory = new RepositoryFactoryHttp(nodeUrl); /* end block 00 */ /* start block 01 */ // replace with recipient address const rawAddress = 'TBONKW-COWBZY-ZB2I5J-D3LSDB-QVBYHB-757VN3-SKPP'; const recipientAddress = Address.createFromRawAddress(rawAddress); const networkType = await repositoryFactory.getNetworkType().toPromise(); // replace with nem.xem id const networkCurrencyMosaicId = new MosaicId('75AF035421401EF0'); // replace with network currency divisibility const networkCurrencyDivisibility = 6; const transferTransaction = TransferTransaction.create( Deadline.create(), recipientAddress, [new Mosaic(networkCurrencyMosaicId, UInt64.fromUint(10 * Math.pow(10, networkCurrencyDivisibility)))], PlainMessage.create('This is a test message'), networkType, UInt64.fromUint(2000000)); /* end block 01 */ /* start block 02 */ // replace with sender private key const privateKey = '1111111111111111111111111111111111111111111111111111111111111111'; const account = Account.createFromPrivateKey(privateKey, networkType); const networkGenerationHash = await repositoryFactory.getGenerationHash().toPromise(); const signedTransaction = account.sign(transferTransaction, networkGenerationHash); /* end block 02 */ /* start block 03 */ // replace with node endpoint const transactionHttp = repositoryFactory.createTransactionRepository(); transactionHttp .announce(signedTransaction) .subscribe((x) => console.log(x), (err) => console.error(err)); /* end block 03 */ }Please note the:
- async await function to simplify the examples. The alternative is to use nested observables, I reckon this is simpler when showing a how-to.
const networkType = await repositoryFactory.getNetworkType().toPromise();const networkGenerationHash =await repositoryFactory.getGenerationHash().toPromise();Both values are lazy and cached. They are loaded only and only the first time the get methods are called.
The same example will work for any network type and any generation hash without manually copying configuration. Two less replace with statements
The java samples are fixed in https://github.com/nemtech/nem2-docs/pull/339. TS sample needs to remove the hardcoded network types and generation hashes
Also, we should remove hardcoded network currency information from the examples like:
// replace with symbol.xym id
const networkCurrencyMosaicId = new MosaicId('5E62990DCAC5BE8A');
// replace with network currency divisibility
const networkCurrencyDivisibility = 6;