importjsonimportosimporttimeimporturllib.requestfromsymbolchain.CryptoTypesimportPrivateKeyfromsymbolchain.facade.SymbolFacadeimportSymbolFacadefromsymbolchain.symbol.Metadataimport(metadata_generate_key,metadata_update_value)NODE_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 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.create_embedded_transaction_from_descriptor({'type':'account_metadata_transaction_v1','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},signer_key_pair.public_key))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.create_transaction_from_descriptor({'type':'aggregate_complete_transaction_v3','transactions_hash':facade.hash_embedded_transactions(creation_embedded_txs),'transactions':creation_embedded_txs},signer_key_pair.public_key,fee_multiplier,2*60*60)# 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.create_embedded_transaction_from_descriptor({'type':'account_metadata_transaction_v1','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},signer_key_pair.public_key))# Build the aggregate for the updateupdate_embedded_txs=[update_embedded_tx]update_tx=facade.create_transaction_from_descriptor({'type':'aggregate_complete_transaction_v3','transactions_hash':facade.hash_embedded_transactions(update_embedded_txs),'transactions':update_embedded_txs},signer_key_pair.public_key,fee_multiplier,2*60*60)# 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{SymbolFacade,descriptors,metadataGenerateKey,metadataUpdateValue}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);});constresponse=awaitfetch(`${NODE_URL}/transactionStatus/${transactionHash}`);if(!response.ok){if(404===response.status){console.log(' Transaction status: unknown');continue;}thrownewError(`HTTP ${response.status}`);}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}`);}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 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.createEmbeddedTransactionFromTypedDescriptor(newdescriptors.AccountMetadataTransactionV1Descriptor(signerAddress,scopedMetadataKey,// When creating new metadata, valueSizeDelta// equals value lengthmetadataValue.length,metadataValue),signerKeyPair.publicKey);console.log('Created embedded metadata transaction:');console.log(JSON.stringify(creationEmbeddedTx.toJson(),null,2));// Build the aggregate transactionconstcreationEmbeddedTxs=[creationEmbeddedTx];constcreationTx=facade.createTransactionFromTypedDescriptor(newdescriptors.AggregateCompleteTransactionV3Descriptor(facade.static.hashEmbeddedTransactions(creationEmbeddedTxs),creationEmbeddedTxs,undefined),signerKeyPair.publicKey,feeMultiplier,2*60*60);// 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.createEmbeddedTransactionFromTypedDescriptor(newdescriptors.AccountMetadataTransactionV1Descriptor(signerAddress,scopedMetadataKey,// valueSizeDelta is the difference in length// (can be negative)newValue.length-currentValue.length,updateValue),signerKeyPair.publicKey);// Build the aggregate for the updateconstupdateEmbeddedTxs=[updateEmbeddedTx];constupdateTx=facade.createTransactionFromTypedDescriptor(newdescriptors.AggregateCompleteTransactionV3Descriptor(facade.static.hashEmbeddedTransactions(updateEmbeddedTxs),updateEmbeddedTxs,undefined),signerKeyPair.publicKey,feeMultiplier,2*60*60);// 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;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.KeyPair;importorg.symbol.sdk.symbol.Metadata;importorg.symbol.sdk.symbol.SymbolTransactionFactory;importorg.symbol.sdk.symbol.descriptors.*;importorg.symbol.sdk.symbol.models.*;publicfinalclassAccountMetadata{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);finalStringstatusPath="/transactionStatus/"+transactionHash;finalHttpRequeststatusRequest=HttpRequest.newBuilder(URI.create(nodeUrl+statusPath)).GET().build();finalHttpResponse<String>statusResponse=HTTP_CLIENT.send(statusRequest,BodyHandlers.ofString());if(404==statusResponse.statusCode()){System.out.println(" Transaction status: unknown");continue;}if(2!=statusResponse.statusCode()/100)thrownewIOException("HTTP "+statusResponse.statusCode());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()));}thrownewIOException(String.format("%s not confirmed after 60 seconds",label));}publicstaticvoidmain(finalString[]args){try{newAccountMetadata().run();}catch(finalExceptionex){System.out.println(null==ex.getMessage()?ex.toString():ex.getMessage());}}privatevoidrun()throwsIOException,InterruptedException{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);// 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.createEmbeddedTransactionFromTypedDescriptor(newAccountMetadataTransactionV1Descriptor(signerAddress,scopedMetadataKey,metadataValue.length,metadataValue),signerKeyPair.getPublicKey());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.createTransactionFromTypedDescriptor(newAggregateCompleteTransactionV3Descriptor(SymbolFacade.hashEmbeddedTransactions(creationEmbeddedTxs),creationEmbeddedTxs,null),signerKeyPair.getPublicKey(),feeMultiplier,2*60*60);// 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.createEmbeddedTransactionFromTypedDescriptor(newAccountMetadataTransactionV1Descriptor(signerAddress,scopedMetadataKey,newValue.length-currentValue.length,updateValue),signerKeyPair.getPublicKey());// Build the aggregate for the updatefinalList<EmbeddedTransaction>updateEmbeddedTxs=List.of(updateEmbeddedTx);finalTransactionupdateTx=facade.createTransactionFromTypedDescriptor(newAggregateCompleteTransactionV3Descriptor(SymbolFacade.hashEmbeddedTransactions(updateEmbeddedTxs),updateEmbeddedTxs,null),signerKeyPair.getPublicKey(),feeMultiplier,2*60*60);// 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");}}
# Create the embedded metadata transactioncreation_embedded_tx=(facade.create_embedded_transaction_from_descriptor({'type':'account_metadata_transaction_v1','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},signer_key_pair.public_key))print('Created embedded metadata transaction:')print(json.dumps(creation_embedded_tx.to_json(),indent=2))
// Create the embedded metadata transactionconstcreationEmbeddedTx=facade.createEmbeddedTransactionFromTypedDescriptor(newdescriptors.AccountMetadataTransactionV1Descriptor(signerAddress,scopedMetadataKey,// When creating new metadata, valueSizeDelta// equals value lengthmetadataValue.length,metadataValue),signerKeyPair.publicKey);console.log('Created embedded metadata transaction:');console.log(JSON.stringify(creationEmbeddedTx.toJson(),null,2));
# Build the aggregate transactioncreation_embedded_txs=[creation_embedded_tx]creation_tx=facade.create_transaction_from_descriptor({'type':'aggregate_complete_transaction_v3','transactions_hash':facade.hash_embedded_transactions(creation_embedded_txs),'transactions':creation_embedded_txs},signer_key_pair.public_key,fee_multiplier,2*60*60)
// Build the aggregate transactionconstcreationEmbeddedTxs=[creationEmbeddedTx];constcreationTx=facade.createTransactionFromTypedDescriptor(newdescriptors.AggregateCompleteTransactionV3Descriptor(facade.static.hashEmbeddedTransactions(creationEmbeddedTxs),creationEmbeddedTxs,undefined),signerKeyPair.publicKey,feeMultiplier,2*60*60);
// Build the aggregate transactionfinalList<EmbeddedTransaction>creationEmbeddedTxs=List.of(creationEmbeddedTx);finalTransactioncreationTx=facade.createTransactionFromTypedDescriptor(newAggregateCompleteTransactionV3Descriptor(SymbolFacade.hashEmbeddedTransactions(creationEmbeddedTxs),creationEmbeddedTxs,null),signerKeyPair.getPublicKey(),feeMultiplier,2*60*60);
# 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.create_embedded_transaction_from_descriptor({'type':'account_metadata_transaction_v1','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},signer_key_pair.public_key))
// XOR the current and new valuesconstnewValue=newTextEncoder().encode('bob');constupdateValue=metadataUpdateValue(currentValue,newValue);// Create the update transaction with XOR'd valueconstupdateEmbeddedTx=facade.createEmbeddedTransactionFromTypedDescriptor(newdescriptors.AccountMetadataTransactionV1Descriptor(signerAddress,scopedMetadataKey,// valueSizeDelta is the difference in length// (can be negative)newValue.length-currentValue.length,updateValue),signerKeyPair.publicKey);
// 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.createEmbeddedTransactionFromTypedDescriptor(newAccountMetadataTransactionV1Descriptor(signerAddress,scopedMetadataKey,newValue.length-currentValue.length,updateValue),signerKeyPair.getPublicKey());
# Build the aggregate for the updateupdate_embedded_txs=[update_embedded_tx]update_tx=facade.create_transaction_from_descriptor({'type':'aggregate_complete_transaction_v3','transactions_hash':facade.hash_embedded_transactions(update_embedded_txs),'transactions':update_embedded_txs},signer_key_pair.public_key,fee_multiplier,2*60*60)# 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.createTransactionFromTypedDescriptor(newdescriptors.AggregateCompleteTransactionV3Descriptor(facade.static.hashEmbeddedTransactions(updateEmbeddedTxs),updateEmbeddedTxs,undefined),signerKeyPair.publicKey,feeMultiplier,2*60*60);// 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.createTransactionFromTypedDescriptor(newAggregateCompleteTransactionV3Descriptor(SymbolFacade.hashEmbeddedTransactions(updateEmbeddedTxs),updateEmbeddedTxs,null),signerKeyPair.getPublicKey(),feeMultiplier,2*60*60);// 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");