importjsonimportosimporttimeimporturllib.requestfromsymbolchain.CryptoTypesimportPrivateKeyfromsymbolchain.facade.SymbolFacadeimportSymbolFacadefromsymbolchain.symbol.IdGeneratorimportgenerate_namespace_idfromsymbolchain.symbol.NetworkimportAddressNODE_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}')# Build the namespace namenamespace_name=os.getenv('ROOT_NAMESPACE',f'ns_{int(time.time())}')print(f'Creating root namespace: {namespace_name}')# Build the transactiontransaction=facade.create_transaction_from_descriptor({'type':'namespace_registration_transaction_v1','registration_type':'root','duration':86400,# approximately 30 days'name':namespace_name},signer_key_pair.public_key,fee_multiplier,2*60*60)# Sign transaction and generate final payloadsignature=facade.sign_transaction(signer_key_pair,transaction)json_payload=facade.transaction_factory.attach_signature(transaction,signature)print('Built transaction:')print(json.dumps(transaction.to_json(),indent=2))transaction_hash=facade.hash_transaction(transaction)print(f'Transaction hash: {transaction_hash}')# Announce transactionannounce_transaction(json_payload,'namespace registration')# Wait for confirmationwait_for_confirmation(transaction_hash,'namespace registration')# Retrieve the namespacenamespace_id=generate_namespace_id(namespace_name)print(f'Namespace ID: {namespace_id} (0x{namespace_id:016X})')namespace_path=f'/namespaces/{namespace_id:016X}'print(f'Fetching namespace information from {namespace_path}')withurllib.request.urlopen(f'{NODE_URL}{namespace_path}')asresponse:response_json=json.loads(response.read().decode())namespace_info=response_json['namespace']print('Namespace information:')reg_type=namespace_info['registrationType']print(f' Registration type: {reg_type}')owner_address=Address.from_decoded_address_hex_string(namespace_info['ownerAddress'])print(f' Owner address: {owner_address}')print(f" Start height: {namespace_info['startHeight']}")print(f" End height: {namespace_info['endHeight']}")exceptExceptionase:print(e)
import{PrivateKey}from'symbol-sdk';import{Address,SymbolFacade,descriptors,generateNamespaceId,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);});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);// Build the namespace nameconstnamespaceName=process.env.ROOT_NAMESPACE||`ns_${Date.now()}`;console.log('Creating root namespace:',namespaceName);// Build the transactionconsttransaction=facade.createTransactionFromTypedDescriptor(newdescriptors.NamespaceRegistrationTransactionV1Descriptor(newmodels.NamespaceId(0n),models.NamespaceRegistrationType.ROOT,newmodels.BlockDuration(86400n),// approximately 30 daysundefined,namespaceName),signerKeyPair.publicKey,feeMultiplier,2*60*60);// Sign transaction and generate final payloadconstsignature=facade.signTransaction(signerKeyPair,transaction);constjsonPayload=facade.transactionFactory.static.attachSignature(transaction,signature);console.log('Built transaction:');console.dir(transaction.toJson(),{colors:true});consttransactionHash=facade.hashTransaction(transaction).toString();console.log('Transaction hash:',transactionHash);// Announce transactionawaitannounceTransaction(jsonPayload,'namespace registration');// Wait for confirmationawaitwaitForConfirmation(transactionHash,'namespace registration');// Retrieve the namespaceconstnamespaceId=generateNamespaceId(namespaceName);constnamespaceIdHex=namespaceId.toString(16).toUpperCase().padStart(16,'0');console.log('Namespace ID:',`${namespaceId} (0x${namespaceIdHex})`);constnamespacePath=`/namespaces/${namespaceIdHex}`;console.log('Fetching namespace information from',namespacePath);constnamespaceResponse=awaitfetch(`${NODE_URL}${namespacePath}`);constnamespaceJSON=awaitnamespaceResponse.json();constnamespaceInfo=namespaceJSON.namespace;console.log('Namespace information:');console.log(' Registration type:',namespaceInfo.registrationType);constownerAddress=Address.fromDecodedAddressHexString(namespaceInfo.ownerAddress);console.log(' Owner address:',ownerAddress.toString());console.log(' Start height:',namespaceInfo.startHeight);console.log(' End height:',namespaceInfo.endHeight);}catch(e){console.error(e.message);}
# Build the transactiontransaction=facade.create_transaction_from_descriptor({'type':'namespace_registration_transaction_v1','registration_type':'root','duration':86400,# approximately 30 days'name':namespace_name},signer_key_pair.public_key,fee_multiplier,2*60*60)
// Build the transactionconsttransaction=facade.createTransactionFromTypedDescriptor(newdescriptors.NamespaceRegistrationTransactionV1Descriptor(newmodels.NamespaceId(0n),models.NamespaceRegistrationType.ROOT,newmodels.BlockDuration(86400n),// approximately 30 daysundefined,namespaceName),signerKeyPair.publicKey,feeMultiplier,2*60*60);
// Build the transactionfinalTransactiontransaction=facade.createTransactionFromTypedDescriptor(newNamespaceRegistrationTransactionV1Descriptor(newNamespaceId(0),NamespaceRegistrationType.ROOT,newBlockDuration(86400),// approximately 30 daysnull,namespaceName.getBytes(StandardCharsets.UTF_8)),signerKeyPair.getPublicKey(),feeMultiplier,2*60*60);