importjsonimportosimporttimeimporturllib.requestfromsymbolchain.CryptoTypesimportPrivateKeyfromsymbolchain.facade.SymbolFacadeimportSymbolFacadefromsymbolchain.scimportAmountfromsymbolchain.symbol.FeeCalculatorimportcalculate_transaction_feefromsymbolchain.symbol.Metadataimport(metadata_generate_key,metadata_update_value)fromsymbolchain.symbol.NetworkimportNetworkTimestampNODE_URL=os.getenv('NODE_URL','https://reference.symboltest.net:3001')print(f'Using node {NODE_URL}')# Helper function to announce a transactiondefannounce_transaction(payload,label):print(f'Announcing {label} to /transactions')request=urllib.request.Request(f'{NODE_URL}/transactions',data=payload.encode(),headers={'Content-Type':'application/json'},method='PUT')withurllib.request.urlopen(request)asannounce_response:print(f' Response: {announce_response.read().decode()}')# Helper function to wait for transaction confirmationdefwait_for_confirmation(tx_hash,label):print(f'Waiting for {label} confirmation...')forattemptinrange(60):time.sleep(1)try:url=f'{NODE_URL}/transactionStatus/{tx_hash}'withurllib.request.urlopen(url)asconfirm_response:status=json.loads(confirm_response.read().decode())print(f' Transaction status: {status["group"]}')ifstatus['group']=='confirmed':print(f'{label} confirmed in {attempt} seconds')returnifstatus['group']=='failed':raiseRuntimeError(f'{label} failed: {status["code"]}')excepturllib.error.HTTPError:print(' Transaction status: unknown')raiseTimeoutError(f'{label} not confirmed after 60 seconds')SIGNER_PRIVATE_KEY=os.getenv('SIGNER_PRIVATE_KEY','0000000000000000000000000000000000000000000000000000000000000000')signer_key_pair=SymbolFacade.KeyPair(PrivateKey(SIGNER_PRIVATE_KEY))facade=SymbolFacade('testnet')signer_address=facade.network.public_key_to_address(signer_key_pair.public_key)print(f'Signer address: {signer_address}')try:# Fetch current network timetime_path='/node/time'print(f'Fetching current network time from {time_path}')withurllib.request.urlopen(f'{NODE_URL}{time_path}')asresponse:response_json=json.loads(response.read().decode())receive_timestamp=(response_json['communicationTimestamps']['receiveTimestamp'])timestamp=NetworkTimestamp(int(receive_timestamp))print(f' Network time: {timestamp.timestamp} ms since nemesis')# Fetch recommended feesfee_path='/network/fees/transaction'print(f'Fetching recommended fees from {fee_path}')withurllib.request.urlopen(f'{NODE_URL}{fee_path}')asresponse:response_json=json.loads(response.read().decode())median_multiplier=response_json['medianFeeMultiplier']minimum_multiplier=response_json['minFeeMultiplier']fee_multiplier=max(median_multiplier,minimum_multiplier)print(f' Fee multiplier: {fee_multiplier}')# --- ADDING NEW METADATA ---print('\n--- Adding new metadata ---')# Define metadata key and valuekey_string=f'username_{int(time.time())}'scoped_metadata_key=metadata_generate_key(key_string)metadata_value='alice'.encode('utf8')# Create the embedded metadata transactioncreation_embedded_tx=facade.transaction_factory.create_embedded({'type':'account_metadata_transaction_v1','signer_public_key':signer_key_pair.public_key,'target_address':signer_address,'scoped_metadata_key':scoped_metadata_key,# When creating new metadata, value_size_delta# equals the value length'value_size_delta':len(metadata_value),'value':metadata_value})print('Created embedded metadata transaction:')print(json.dumps(creation_embedded_tx.to_json(),indent=2))# Build the aggregate transactioncreation_embedded_txs=[creation_embedded_tx]creation_tx=facade.transaction_factory.create({'type':'aggregate_complete_transaction_v3','signer_public_key':signer_key_pair.public_key,'deadline':timestamp.add_hours(2).timestamp,'transactions_hash':facade.hash_embedded_transactions(creation_embedded_txs),'transactions':creation_embedded_txs})creation_tx.fee=Amount(calculate_transaction_fee(creation_tx,fee_multiplier))# Sign and generate final payloadsignature=facade.sign_transaction(signer_key_pair,creation_tx)creation_payload=facade.transaction_factory.attach_signature(creation_tx,signature)# Announce and wait for confirmationcreation_tx_hash=facade.hash_transaction(creation_tx)print(f'Built aggregate transaction with hash: {creation_tx_hash}')announce_transaction(creation_payload,'creation transaction')wait_for_confirmation(creation_tx_hash,'creation transaction')# --- MODIFYING EXISTING METADATA ---print('\n--- Modifying existing metadata ---')# Fetch current metadata value from networkmetadata_path=(f'/metadata?sourceAddress={signer_address}'f'&targetAddress={signer_address}'f'&scopedMetadataKey={scoped_metadata_key:016X}''&metadataType=0')print(f'Fetching current metadata from {metadata_path}')withurllib.request.urlopen(f'{NODE_URL}{metadata_path}')asresponse:response_json=json.loads(response.read().decode())# Get the metadata entryifnotresponse_json['data']:raiseRuntimeError('Metadata entry not found')metadata_entry=response_json['data'][0]['metadataEntry']current_value=bytes.fromhex(metadata_entry['value'])print(f' Current value: {current_value.decode("utf8")}')# XOR the current and new valuesnew_value='bob'.encode('utf8')update_value=metadata_update_value(current_value,new_value)# Create the update transaction with XOR'd valueupdate_embedded_tx=facade.transaction_factory.create_embedded({'type':'account_metadata_transaction_v1','signer_public_key':signer_key_pair.public_key,'target_address':signer_address,'scoped_metadata_key':scoped_metadata_key,# value_size_delta is the difference in length# (can be negative)'value_size_delta':len(new_value)-len(current_value),'value':update_value})# Build the aggregate for the updateupdate_embedded_txs=[update_embedded_tx]update_tx=facade.transaction_factory.create({'type':'aggregate_complete_transaction_v3','signer_public_key':signer_key_pair.public_key,'deadline':timestamp.add_hours(2).timestamp,'transactions_hash':facade.hash_embedded_transactions(update_embedded_txs),'transactions':update_embedded_txs})update_tx.fee=Amount(calculate_transaction_fee(update_tx,fee_multiplier))# Sign and announce the updatesignature=facade.sign_transaction(signer_key_pair,update_tx)update_payload=facade.transaction_factory.attach_signature(update_tx,signature)# Announce and wait for confirmationupdate_tx_hash=facade.hash_transaction(update_tx)print(f'Built aggregate transaction with hash: {update_tx_hash}')announce_transaction(update_payload,'update transaction')wait_for_confirmation(update_tx_hash,'update transaction')exceptExceptionase:print(e)
import{PrivateKey}from'symbol-sdk';import{NetworkTimestamp,SymbolFacade,calculateTransactionFee,metadataGenerateKey,metadataUpdateValue,models}from'symbol-sdk/symbol';constNODE_URL=process.env.NODE_URL||'https://reference.symboltest.net:3001';console.log('Using node',NODE_URL);// Helper function to announce a transactionasyncfunctionannounceTransaction(payload,label){console.log(`Announcing ${label} to /transactions`);constresponse=awaitfetch(`${NODE_URL}/transactions`,{method:'PUT',headers:{'Content-Type':'application/json'},body:payload});console.log(' Response:',awaitresponse.text());}// Helper function to wait for transaction confirmationasyncfunctionwaitForConfirmation(transactionHash,label){console.log(`Waiting for ${label} confirmation...`);for(letattempt=0;60>attempt;attempt++){awaitnewPromise(resolve=>{setTimeout(resolve,1000);});try{constresponse=awaitfetch(`${NODE_URL}/transactionStatus/${transactionHash}`);conststatus=awaitresponse.json();console.log(' Transaction status:',status.group);if('confirmed'===status.group){console.log(`${label} confirmed in`,attempt,'seconds');return;}if('failed'===status.group)thrownewError(`${label} failed: ${status.code}`);}catch(e){if(e.message.includes('failed'))throwe;console.log(' Transaction status: unknown');}}thrownewError(`${label} not confirmed after 60 seconds`);}constSIGNER_PRIVATE_KEY=process.env.SIGNER_PRIVATE_KEY||('0000000000000000000000000000000000000000000000000000000000000000');constsignerKeyPair=newSymbolFacade.KeyPair(newPrivateKey(SIGNER_PRIVATE_KEY));constfacade=newSymbolFacade('testnet');constsignerAddress=facade.network.publicKeyToAddress(signerKeyPair.publicKey);console.log('Signer address:',signerAddress.toString());try{// Fetch current network timeconsttimePath='/node/time';console.log('Fetching current network time from',timePath);consttimeResponse=awaitfetch(`${NODE_URL}${timePath}`);consttimeJSON=awaittimeResponse.json();consttimestamp=newNetworkTimestamp(timeJSON.communicationTimestamps.receiveTimestamp);console.log(' Network time:',timestamp.timestamp,'ms since nemesis');// Fetch recommended feesconstfeePath='/network/fees/transaction';console.log('Fetching recommended fees from',feePath);constfeeResponse=awaitfetch(`${NODE_URL}${feePath}`);constfeeJSON=awaitfeeResponse.json();constmedianMultiplier=feeJSON.medianFeeMultiplier;constminimumMultiplier=feeJSON.minFeeMultiplier;constfeeMultiplier=Math.max(medianMultiplier,minimumMultiplier);console.log(' Fee multiplier:',feeMultiplier);// --- ADDING NEW METADATA ---console.log('\n--- Adding new metadata ---');// Define metadata key and valueconstkeyString=`username_${Date.now()}`;constscopedMetadataKey=metadataGenerateKey(keyString);constmetadataValue=newTextEncoder().encode('alice');// Create the embedded metadata transactionconstcreationEmbeddedTx=facade.transactionFactory.createEmbedded({type:'account_metadata_transaction_v1',signerPublicKey:signerKeyPair.publicKey.toString(),targetAddress:signerAddress.toString(),scopedMetadataKey,// When creating new metadata, valueSizeDelta// equals value lengthvalueSizeDelta:metadataValue.length,value:metadataValue});console.log('Created embedded metadata transaction:');console.log(JSON.stringify(creationEmbeddedTx.toJson(),null,2));// Build the aggregate transactionconstcreationEmbeddedTxs=[creationEmbeddedTx];constcreationTx=facade.transactionFactory.create({type:'aggregate_complete_transaction_v3',signerPublicKey:signerKeyPair.publicKey.toString(),deadline:timestamp.addHours(2).timestamp,transactionsHash:facade.static.hashEmbeddedTransactions(creationEmbeddedTxs),transactions:creationEmbeddedTxs});creationTx.fee=newmodels.Amount(calculateTransactionFee(creationTx,feeMultiplier));// Sign and generate final payloadconstsignature=facade.signTransaction(signerKeyPair,creationTx);constcreationPayload=facade.transactionFactory.static.attachSignature(creationTx,signature);// Announce and wait for confirmationconstcreationTxHash=facade.hashTransaction(creationTx).toString();console.log('Built aggregate transaction with hash:',creationTxHash);awaitannounceTransaction(creationPayload,'creation transaction');awaitwaitForConfirmation(creationTxHash,'creation transaction');// --- MODIFYING EXISTING METADATA ---console.log('\n--- Modifying existing metadata ---');// Fetch current metadata value from networkconstscopedKeyHex=scopedMetadataKey.toString(16).toUpperCase().padStart(16,'0');constmetadataPath=`/metadata?sourceAddress=${signerAddress}`+`&targetAddress=${signerAddress}`+`&scopedMetadataKey=${scopedKeyHex}`+'&metadataType=0';console.log('Fetching current metadata from',metadataPath);constmetadataResponse=awaitfetch(`${NODE_URL}${metadataPath}`);constmetadataJSON=awaitmetadataResponse.json();// Get the metadata entryif(!metadataJSON.data.length)thrownewError('Metadata entry not found');constmetadataEntry=metadataJSON.data[0].metadataEntry;constcurrentValue=Buffer.from(metadataEntry.value,'hex');console.log(' Current value:',currentValue.toString('utf8'));// XOR the current and new valuesconstnewValue=newTextEncoder().encode('bob');constupdateValue=metadataUpdateValue(currentValue,newValue);// Create the update transaction with XOR'd valueconstupdateEmbeddedTx=facade.transactionFactory.createEmbedded({type:'account_metadata_transaction_v1',signerPublicKey:signerKeyPair.publicKey.toString(),targetAddress:signerAddress.toString(),scopedMetadataKey,// valueSizeDelta is the difference in length// (can be negative)valueSizeDelta:newValue.length-currentValue.length,value:updateValue});// Build the aggregate for the updateconstupdateEmbeddedTxs=[updateEmbeddedTx];constupdateTx=facade.transactionFactory.create({type:'aggregate_complete_transaction_v3',signerPublicKey:signerKeyPair.publicKey.toString(),deadline:timestamp.addHours(2).timestamp,transactionsHash:facade.static.hashEmbeddedTransactions(updateEmbeddedTxs),transactions:updateEmbeddedTxs});updateTx.fee=newmodels.Amount(calculateTransactionFee(updateTx,feeMultiplier));// Sign and announce the updateconstupdateSignature=facade.signTransaction(signerKeyPair,updateTx);constupdatePayload=facade.transactionFactory.static.attachSignature(updateTx,updateSignature);// Announce and wait for confirmationconstupdateTxHash=facade.hashTransaction(updateTx).toString();console.log('Built aggregate transaction with hash:',updateTxHash);awaitannounceTransaction(updatePayload,'update transaction');awaitwaitForConfirmation(updateTxHash,'update transaction');}catch(e){console.error(e.message,'| Cause:',e.cause?.code??'unknown');}
//JAVA 21+//DEPS org.symbol:symbol-sdk:3.3.1importjava.io.IOException;importjava.net.URI;importjava.net.http.HttpClient;importjava.net.http.HttpRequest;importjava.net.http.HttpResponse;importjava.net.http.HttpResponse.BodyHandlers;importjava.nio.charset.StandardCharsets;importjava.util.List;importjava.util.Map;importcom.fasterxml.jackson.databind.JsonNode;importcom.fasterxml.jackson.databind.ObjectMapper;importorg.symbol.sdk.CryptoTypes;importorg.symbol.sdk.facade.SymbolFacade;importorg.symbol.sdk.symbol.Address;importorg.symbol.sdk.symbol.FeeCalculator;importorg.symbol.sdk.symbol.KeyPair;importorg.symbol.sdk.symbol.Metadata;importorg.symbol.sdk.symbol.NetworkTimestamp;importorg.symbol.sdk.symbol.SymbolTransactionFactory;importorg.symbol.sdk.symbol.models.*;finalclassAccountMetadata{privatestaticfinalObjectMapperJSON_MAPPER=newObjectMapper();privatestaticfinalHttpClientHTTP_CLIENT=HttpClient.newHttpClient();privatefinalStringnodeUrl=System.getenv().getOrDefault("NODE_URL","https://reference.symboltest.net:3001");privatefinalSymbolFacadefacade=newSymbolFacade("testnet");privatevoidannounceTransaction(finalStringpayload,finalStringlabel)throwsIOException,InterruptedException{System.out.printf("Announcing %s to /transactions%n",label);finalHttpRequestrequest=HttpRequest.newBuilder(URI.create(nodeUrl+"/transactions")).header("Content-Type","application/json").PUT(HttpRequest.BodyPublishers.ofString(payload)).build();finalHttpResponse<String>response=HTTP_CLIENT.send(request,BodyHandlers.ofString());System.out.printf(" Response: %s%n",response.body());}privatevoidwaitForConfirmation(finalStringtransactionHash,finalStringlabel)throwsIOException,InterruptedException{System.out.printf("Waiting for %s confirmation...%n",label);for(intattempt=0;60>attempt;++attempt){Thread.sleep(1000);try{finalStringstatusPath="/transactionStatus/"+transactionHash;finalHttpRequeststatusRequest=HttpRequest.newBuilder(URI.create(nodeUrl+statusPath)).GET().build();finalHttpResponse<String>statusResponse=HTTP_CLIENT.send(statusRequest,BodyHandlers.ofString());finalJsonNodestatus=JSON_MAPPER.readTree(statusResponse.body());finalStringgroup=status.get("group").asText();System.out.printf(" Transaction status: %s%n",group);if("confirmed".equals(group)){System.out.printf("%s confirmed in %d seconds%n",label,attempt);return;}if("failed".equals(group))thrownewIOException(String.format("%s failed: %s",label,status.get("code").asText()));}catch(finalIOExceptionex){if(ex.getMessage().contains("failed"))throwex;System.out.println(" Transaction status: unknown");}}thrownewIOException(String.format("%s not confirmed after 60 seconds",label));}publicstaticvoidmain(finalString[]args){newAccountMetadata().run();}privatevoidrun(){System.out.printf("Using node %s%n",nodeUrl);finalStringprivateKeyString=System.getenv().getOrDefault("SIGNER_PRIVATE_KEY","0".repeat(64));finalKeyPairsignerKeyPair=newKeyPair(newCryptoTypes.PrivateKey(privateKeyString));finalAddresssignerAddress=facade.network.publicKeyToAddress(signerKeyPair.getPublicKey());System.out.printf("Signer address: %s%n",signerAddress);try{// Fetch current network timefinalStringtimePath="/node/time";System.out.printf("Fetching current network time from %s%n",timePath);finalHttpRequesttimeRequest=HttpRequest.newBuilder(URI.create(nodeUrl+timePath)).GET().build();finalHttpResponse<String>timeResponse=HTTP_CLIENT.send(timeRequest,BodyHandlers.ofString());finalJsonNodetimeJson=JSON_MAPPER.readTree(timeResponse.body());finalNetworkTimestamptimestamp=newNetworkTimestamp(timeJson.get("communicationTimestamps").get("receiveTimestamp").asLong());System.out.printf(" Network time: %dms since nemesis%n",timestamp.timestamp);// Fetch recommended feesfinalStringfeePath="/network/fees/transaction";System.out.printf("Fetching recommended fees from %s%n",feePath);finalHttpRequestfeeRequest=HttpRequest.newBuilder(URI.create(nodeUrl+feePath)).GET().build();finalHttpResponse<String>feeResponse=HTTP_CLIENT.send(feeRequest,BodyHandlers.ofString());finalJsonNodefeeJson=JSON_MAPPER.readTree(feeResponse.body());finallongfeeMultiplier=Math.max(feeJson.get("medianFeeMultiplier").asLong(),feeJson.get("minFeeMultiplier").asLong());System.out.printf(" Fee multiplier: %d%n",feeMultiplier);System.out.println("\n--- Adding new metadata ---");// Define metadata key and valuefinalStringkeyString=String.format("username_%d",System.currentTimeMillis());finallongscopedMetadataKey=Metadata.generateKey(keyString);finalbyte[]metadataValue="alice".getBytes(StandardCharsets.UTF_8);// Create the embedded metadata transactionfinalEmbeddedTransactioncreationEmbeddedTx=facade.transactionFactory.createEmbedded(Map.of("type","account_metadata_transaction_v1","signerPublicKey",signerKeyPair.getPublicKey(),"targetAddress",signerAddress,"scopedMetadataKey",scopedMetadataKey,// When creating new metadata, valueSizeDelta// equals the value length"valueSizeDelta",metadataValue.length,// Cast one value to infer Map<String, Object>,// as expected by the SDK."value",(Object)metadataValue));System.out.println("Created embedded metadata transaction:");System.out.println(JSON_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(creationEmbeddedTx.toJson()));// Build the aggregate transactionfinalList<EmbeddedTransaction>creationEmbeddedTxs=List.of(creationEmbeddedTx);finalTransactioncreationTx=facade.transactionFactory.create(Map.of("type","aggregate_complete_transaction_v3","signerPublicKey",signerKeyPair.getPublicKey(),"deadline",timestamp.addHours(2).timestamp,"transactionsHash",SymbolFacade.hashEmbeddedTransactions(creationEmbeddedTxs),// Cast one value to infer Map<String, Object>,// as expected by the SDK."transactions",(Object)creationEmbeddedTxs));creationTx.setFee(newAmount(FeeCalculator.calculateTransactionFee(creationTx,feeMultiplier)));// Sign and generate final payloadfinalStringcreationPayload=SymbolTransactionFactory.attachSignature(creationTx,facade.signTransaction(signerKeyPair,creationTx));// Announce and wait for confirmationfinalStringcreationTxHash=facade.hashTransaction(creationTx).toString();System.out.printf("Built aggregate transaction with hash: %s%n",creationTxHash);announceTransaction(creationPayload,"creation transaction");waitForConfirmation(creationTxHash,"creation transaction");System.out.println("\n--- Modifying existing metadata ---");// Fetch current metadata value from networkfinalStringscopedKeyHex="%016X".formatted(scopedMetadataKey);finalStringmetadataPath=String.format("/metadata?sourceAddress=%s&targetAddress=%s"+"&scopedMetadataKey=%s&metadataType=0",signerAddress,signerAddress,scopedKeyHex);System.out.printf("Fetching current metadata from %s%n",metadataPath);finalHttpRequestmetadataRequest=HttpRequest.newBuilder(URI.create(nodeUrl+metadataPath)).GET().build();finalHttpResponse<String>metadataResponse=HTTP_CLIENT.send(metadataRequest,BodyHandlers.ofString());finalJsonNodemetadataJson=JSON_MAPPER.readTree(metadataResponse.body());// Get the metadata entryfinalJsonNodemetadataData=metadataJson.get("data");if(null==metadataData)thrownewIOException("Unexpected metadata response: "+metadataJson);if(metadataData.isEmpty())thrownewIOException("Metadata entry not found");finalJsonNodemetadataEntry=metadataData.get(0).get("metadataEntry");finalbyte[]currentValue=java.util.HexFormat.of().parseHex(metadataEntry.get("value").asText());System.out.printf(" Current value: %s%n",newString(currentValue,StandardCharsets.UTF_8));// XOR the current and new valuesfinalbyte[]newValue="bob".getBytes(StandardCharsets.UTF_8);finalbyte[]updateValue=Metadata.updateValue(currentValue,newValue);// Create the update transaction with XOR'd valuefinalEmbeddedTransactionupdateEmbeddedTx=facade.transactionFactory.createEmbedded(Map.of("type","account_metadata_transaction_v1","signerPublicKey",signerKeyPair.getPublicKey(),"targetAddress",signerAddress,"scopedMetadataKey",scopedMetadataKey,// valueSizeDelta is the difference in length// (can be negative)"valueSizeDelta",newValue.length-currentValue.length,// Cast one value to infer Map<String, Object>,// as expected by the SDK."value",(Object)updateValue));// Build the aggregate for the updatefinalList<EmbeddedTransaction>updateEmbeddedTxs=List.of(updateEmbeddedTx);finalTransactionupdateTx=facade.transactionFactory.create(Map.of("type","aggregate_complete_transaction_v3","signerPublicKey",signerKeyPair.getPublicKey(),"deadline",timestamp.addHours(2).timestamp,"transactionsHash",SymbolFacade.hashEmbeddedTransactions(updateEmbeddedTxs),// Cast one value to infer Map<String, Object>,// as expected by the SDK."transactions",(Object)updateEmbeddedTxs));updateTx.setFee(newAmount(FeeCalculator.calculateTransactionFee(updateTx,feeMultiplier)));// Sign and announce the updatefinalStringupdatePayload=SymbolTransactionFactory.attachSignature(updateTx,facade.signTransaction(signerKeyPair,updateTx));// Announce and wait for confirmationfinalStringupdateTxHash=facade.hashTransaction(updateTx).toString();System.out.printf("Built aggregate transaction with hash: %s%n",updateTxHash);announceTransaction(updatePayload,"update transaction");waitForConfirmation(updateTxHash,"update transaction");}catch(finalExceptionex){System.out.println(ex.getMessage());}}}
# Fetch current network timetime_path='/node/time'print(f'Fetching current network time from {time_path}')withurllib.request.urlopen(f'{NODE_URL}{time_path}')asresponse:response_json=json.loads(response.read().decode())receive_timestamp=(response_json['communicationTimestamps']['receiveTimestamp'])timestamp=NetworkTimestamp(int(receive_timestamp))print(f' Network time: {timestamp.timestamp} ms since nemesis')# Fetch recommended feesfee_path='/network/fees/transaction'print(f'Fetching recommended fees from {fee_path}')withurllib.request.urlopen(f'{NODE_URL}{fee_path}')asresponse:response_json=json.loads(response.read().decode())median_multiplier=response_json['medianFeeMultiplier']minimum_multiplier=response_json['minFeeMultiplier']fee_multiplier=max(median_multiplier,minimum_multiplier)print(f' Fee multiplier: {fee_multiplier}')
// Fetch current network timefinalStringtimePath="/node/time";System.out.printf("Fetching current network time from %s%n",timePath);finalHttpRequesttimeRequest=HttpRequest.newBuilder(URI.create(nodeUrl+timePath)).GET().build();finalHttpResponse<String>timeResponse=HTTP_CLIENT.send(timeRequest,BodyHandlers.ofString());finalJsonNodetimeJson=JSON_MAPPER.readTree(timeResponse.body());finalNetworkTimestamptimestamp=newNetworkTimestamp(timeJson.get("communicationTimestamps").get("receiveTimestamp").asLong());System.out.printf(" Network time: %dms since nemesis%n",timestamp.timestamp);// Fetch recommended feesfinalStringfeePath="/network/fees/transaction";System.out.printf("Fetching recommended fees from %s%n",feePath);finalHttpRequestfeeRequest=HttpRequest.newBuilder(URI.create(nodeUrl+feePath)).GET().build();finalHttpResponse<String>feeResponse=HTTP_CLIENT.send(feeRequest,BodyHandlers.ofString());finalJsonNodefeeJson=JSON_MAPPER.readTree(feeResponse.body());finallongfeeMultiplier=Math.max(feeJson.get("medianFeeMultiplier").asLong(),feeJson.get("minFeeMultiplier").asLong());System.out.printf(" Fee multiplier: %d%n",feeMultiplier);
# Create the embedded metadata transactioncreation_embedded_tx=facade.transaction_factory.create_embedded({'type':'account_metadata_transaction_v1','signer_public_key':signer_key_pair.public_key,'target_address':signer_address,'scoped_metadata_key':scoped_metadata_key,# When creating new metadata, value_size_delta# equals the value length'value_size_delta':len(metadata_value),'value':metadata_value})print('Created embedded metadata transaction:')print(json.dumps(creation_embedded_tx.to_json(),indent=2))
// Create the embedded metadata transactionconstcreationEmbeddedTx=facade.transactionFactory.createEmbedded({type:'account_metadata_transaction_v1',signerPublicKey:signerKeyPair.publicKey.toString(),targetAddress:signerAddress.toString(),scopedMetadataKey,// When creating new metadata, valueSizeDelta// equals value lengthvalueSizeDelta:metadataValue.length,value:metadataValue});console.log('Created embedded metadata transaction:');console.log(JSON.stringify(creationEmbeddedTx.toJson(),null,2));
// Create the embedded metadata transactionfinalEmbeddedTransactioncreationEmbeddedTx=facade.transactionFactory.createEmbedded(Map.of("type","account_metadata_transaction_v1","signerPublicKey",signerKeyPair.getPublicKey(),"targetAddress",signerAddress,"scopedMetadataKey",scopedMetadataKey,// When creating new metadata, valueSizeDelta// equals the value length"valueSizeDelta",metadataValue.length,// Cast one value to infer Map<String, Object>,// as expected by the SDK."value",(Object)metadataValue));System.out.println("Created embedded metadata transaction:");System.out.println(JSON_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(creationEmbeddedTx.toJson()));
# Build the aggregate transactioncreation_embedded_txs=[creation_embedded_tx]creation_tx=facade.transaction_factory.create({'type':'aggregate_complete_transaction_v3','signer_public_key':signer_key_pair.public_key,'deadline':timestamp.add_hours(2).timestamp,'transactions_hash':facade.hash_embedded_transactions(creation_embedded_txs),'transactions':creation_embedded_txs})creation_tx.fee=Amount(calculate_transaction_fee(creation_tx,fee_multiplier))
// Build the aggregate transactionconstcreationEmbeddedTxs=[creationEmbeddedTx];constcreationTx=facade.transactionFactory.create({type:'aggregate_complete_transaction_v3',signerPublicKey:signerKeyPair.publicKey.toString(),deadline:timestamp.addHours(2).timestamp,transactionsHash:facade.static.hashEmbeddedTransactions(creationEmbeddedTxs),transactions:creationEmbeddedTxs});creationTx.fee=newmodels.Amount(calculateTransactionFee(creationTx,feeMultiplier));
// Build the aggregate transactionfinalList<EmbeddedTransaction>creationEmbeddedTxs=List.of(creationEmbeddedTx);finalTransactioncreationTx=facade.transactionFactory.create(Map.of("type","aggregate_complete_transaction_v3","signerPublicKey",signerKeyPair.getPublicKey(),"deadline",timestamp.addHours(2).timestamp,"transactionsHash",SymbolFacade.hashEmbeddedTransactions(creationEmbeddedTxs),// Cast one value to infer Map<String, Object>,// as expected by the SDK."transactions",(Object)creationEmbeddedTxs));creationTx.setFee(newAmount(FeeCalculator.calculateTransactionFee(creationTx,feeMultiplier)));
# Sign and generate final payloadsignature=facade.sign_transaction(signer_key_pair,creation_tx)creation_payload=facade.transaction_factory.attach_signature(creation_tx,signature)# Announce and wait for confirmationcreation_tx_hash=facade.hash_transaction(creation_tx)print(f'Built aggregate transaction with hash: {creation_tx_hash}')announce_transaction(creation_payload,'creation transaction')wait_for_confirmation(creation_tx_hash,'creation transaction')
// Sign and generate final payloadconstsignature=facade.signTransaction(signerKeyPair,creationTx);constcreationPayload=facade.transactionFactory.static.attachSignature(creationTx,signature);// Announce and wait for confirmationconstcreationTxHash=facade.hashTransaction(creationTx).toString();console.log('Built aggregate transaction with hash:',creationTxHash);awaitannounceTransaction(creationPayload,'creation transaction');awaitwaitForConfirmation(creationTxHash,'creation transaction');
// Sign and generate final payloadfinalStringcreationPayload=SymbolTransactionFactory.attachSignature(creationTx,facade.signTransaction(signerKeyPair,creationTx));// Announce and wait for confirmationfinalStringcreationTxHash=facade.hashTransaction(creationTx).toString();System.out.printf("Built aggregate transaction with hash: %s%n",creationTxHash);announceTransaction(creationPayload,"creation transaction");waitForConfirmation(creationTxHash,"creation transaction");
# Fetch current metadata value from networkmetadata_path=(f'/metadata?sourceAddress={signer_address}'f'&targetAddress={signer_address}'f'&scopedMetadataKey={scoped_metadata_key:016X}''&metadataType=0')print(f'Fetching current metadata from {metadata_path}')withurllib.request.urlopen(f'{NODE_URL}{metadata_path}')asresponse:response_json=json.loads(response.read().decode())# Get the metadata entryifnotresponse_json['data']:raiseRuntimeError('Metadata entry not found')metadata_entry=response_json['data'][0]['metadataEntry']current_value=bytes.fromhex(metadata_entry['value'])print(f' Current value: {current_value.decode("utf8")}')
// Fetch current metadata value from networkconstscopedKeyHex=scopedMetadataKey.toString(16).toUpperCase().padStart(16,'0');constmetadataPath=`/metadata?sourceAddress=${signerAddress}`+`&targetAddress=${signerAddress}`+`&scopedMetadataKey=${scopedKeyHex}`+'&metadataType=0';console.log('Fetching current metadata from',metadataPath);constmetadataResponse=awaitfetch(`${NODE_URL}${metadataPath}`);constmetadataJSON=awaitmetadataResponse.json();// Get the metadata entryif(!metadataJSON.data.length)thrownewError('Metadata entry not found');constmetadataEntry=metadataJSON.data[0].metadataEntry;constcurrentValue=Buffer.from(metadataEntry.value,'hex');console.log(' Current value:',currentValue.toString('utf8'));
// Fetch current metadata value from networkfinalStringscopedKeyHex="%016X".formatted(scopedMetadataKey);finalStringmetadataPath=String.format("/metadata?sourceAddress=%s&targetAddress=%s"+"&scopedMetadataKey=%s&metadataType=0",signerAddress,signerAddress,scopedKeyHex);System.out.printf("Fetching current metadata from %s%n",metadataPath);finalHttpRequestmetadataRequest=HttpRequest.newBuilder(URI.create(nodeUrl+metadataPath)).GET().build();finalHttpResponse<String>metadataResponse=HTTP_CLIENT.send(metadataRequest,BodyHandlers.ofString());finalJsonNodemetadataJson=JSON_MAPPER.readTree(metadataResponse.body());// Get the metadata entryfinalJsonNodemetadataData=metadataJson.get("data");if(null==metadataData)thrownewIOException("Unexpected metadata response: "+metadataJson);if(metadataData.isEmpty())thrownewIOException("Metadata entry not found");finalJsonNodemetadataEntry=metadataData.get(0).get("metadataEntry");finalbyte[]currentValue=java.util.HexFormat.of().parseHex(metadataEntry.get("value").asText());System.out.printf(" Current value: %s%n",newString(currentValue,StandardCharsets.UTF_8));
# XOR the current and new valuesnew_value='bob'.encode('utf8')update_value=metadata_update_value(current_value,new_value)# Create the update transaction with XOR'd valueupdate_embedded_tx=facade.transaction_factory.create_embedded({'type':'account_metadata_transaction_v1','signer_public_key':signer_key_pair.public_key,'target_address':signer_address,'scoped_metadata_key':scoped_metadata_key,# value_size_delta is the difference in length# (can be negative)'value_size_delta':len(new_value)-len(current_value),'value':update_value})
// XOR the current and new valuesconstnewValue=newTextEncoder().encode('bob');constupdateValue=metadataUpdateValue(currentValue,newValue);// Create the update transaction with XOR'd valueconstupdateEmbeddedTx=facade.transactionFactory.createEmbedded({type:'account_metadata_transaction_v1',signerPublicKey:signerKeyPair.publicKey.toString(),targetAddress:signerAddress.toString(),scopedMetadataKey,// valueSizeDelta is the difference in length// (can be negative)valueSizeDelta:newValue.length-currentValue.length,value:updateValue});
// XOR the current and new valuesfinalbyte[]newValue="bob".getBytes(StandardCharsets.UTF_8);finalbyte[]updateValue=Metadata.updateValue(currentValue,newValue);// Create the update transaction with XOR'd valuefinalEmbeddedTransactionupdateEmbeddedTx=facade.transactionFactory.createEmbedded(Map.of("type","account_metadata_transaction_v1","signerPublicKey",signerKeyPair.getPublicKey(),"targetAddress",signerAddress,"scopedMetadataKey",scopedMetadataKey,// valueSizeDelta is the difference in length// (can be negative)"valueSizeDelta",newValue.length-currentValue.length,// Cast one value to infer Map<String, Object>,// as expected by the SDK."value",(Object)updateValue));
# Build the aggregate for the updateupdate_embedded_txs=[update_embedded_tx]update_tx=facade.transaction_factory.create({'type':'aggregate_complete_transaction_v3','signer_public_key':signer_key_pair.public_key,'deadline':timestamp.add_hours(2).timestamp,'transactions_hash':facade.hash_embedded_transactions(update_embedded_txs),'transactions':update_embedded_txs})update_tx.fee=Amount(calculate_transaction_fee(update_tx,fee_multiplier))# Sign and announce the updatesignature=facade.sign_transaction(signer_key_pair,update_tx)update_payload=facade.transaction_factory.attach_signature(update_tx,signature)# Announce and wait for confirmationupdate_tx_hash=facade.hash_transaction(update_tx)print(f'Built aggregate transaction with hash: {update_tx_hash}')announce_transaction(update_payload,'update transaction')wait_for_confirmation(update_tx_hash,'update transaction')
// Build the aggregate for the updateconstupdateEmbeddedTxs=[updateEmbeddedTx];constupdateTx=facade.transactionFactory.create({type:'aggregate_complete_transaction_v3',signerPublicKey:signerKeyPair.publicKey.toString(),deadline:timestamp.addHours(2).timestamp,transactionsHash:facade.static.hashEmbeddedTransactions(updateEmbeddedTxs),transactions:updateEmbeddedTxs});updateTx.fee=newmodels.Amount(calculateTransactionFee(updateTx,feeMultiplier));// Sign and announce the updateconstupdateSignature=facade.signTransaction(signerKeyPair,updateTx);constupdatePayload=facade.transactionFactory.static.attachSignature(updateTx,updateSignature);// Announce and wait for confirmationconstupdateTxHash=facade.hashTransaction(updateTx).toString();console.log('Built aggregate transaction with hash:',updateTxHash);awaitannounceTransaction(updatePayload,'update transaction');awaitwaitForConfirmation(updateTxHash,'update transaction');
// Build the aggregate for the updatefinalList<EmbeddedTransaction>updateEmbeddedTxs=List.of(updateEmbeddedTx);finalTransactionupdateTx=facade.transactionFactory.create(Map.of("type","aggregate_complete_transaction_v3","signerPublicKey",signerKeyPair.getPublicKey(),"deadline",timestamp.addHours(2).timestamp,"transactionsHash",SymbolFacade.hashEmbeddedTransactions(updateEmbeddedTxs),// Cast one value to infer Map<String, Object>,// as expected by the SDK."transactions",(Object)updateEmbeddedTxs));updateTx.setFee(newAmount(FeeCalculator.calculateTransactionFee(updateTx,feeMultiplier)));// Sign and announce the updatefinalStringupdatePayload=SymbolTransactionFactory.attachSignature(updateTx,facade.signTransaction(signerKeyPair,updateTx));// Announce and wait for confirmationfinalStringupdateTxHash=facade.hashTransaction(updateTx).toString();System.out.printf("Built aggregate transaction with hash: %s%n",updateTxHash);announceTransaction(updatePayload,"update transaction");waitForConfirmation(updateTxHash,"update transaction");