importjsonimportosimporttimeimporturllib.request# ConfigurationNODE_URL=os.getenv("NODE_URL","https://reference.symboltest.net:3001")print(f'Using node {NODE_URL}')# Transaction hash to monitortransaction_hash=os.getenv("TRANSACTION_HASH","2B6D3B5232E06B9D32682F518C765301FCF9716BFA1EEEF9523653406E04C7EA")print(f"Monitoring transaction: {transaction_hash}")defwait_for_transaction_confirmation(tx_hash,max_attempts=60,wait_seconds=2):""" Poll the transaction status endpoint until the transaction is confirmed. Args: tx_hash: The hash of the transaction to monitor max_attempts: Maximum number of polling attempts for confirmation wait_seconds: Seconds to wait between attempts Returns: True if transaction was confirmed """status_path=f"/transactionStatus/{tx_hash}"print("\nWaiting for transaction confirmation")print(f"Polling {status_path}")forattemptinrange(1,max_attempts+1):try:# Query the transaction status endpointurl=f"{NODE_URL}{status_path}"withurllib.request.urlopen(url)asresponse:response_json=json.loads(response.read().decode())# Parse the responsestatus_group=response_json["group"]status_code=response_json["code"]status_hash=response_json["hash"]status_deadline=response_json["deadline"]print(f" Attempt {attempt}:")print(f" Status: {status_group}")print(f" Code: {status_code}")print(f" Hash: {status_hash}")print(f" Deadline: {status_deadline}")# Check if the transaction has been confirmedifstatus_group=="confirmed":print("\nTransaction confirmed!")returnTrue# Check if the transaction failedifstatus_group=="failed":print(f"\nTransaction failed with code: {status_code}")raiseRuntimeError(f"Transaction failed: {status_code}")excepturllib.error.HTTPErroraserr:iferr.status==404:print(f" Attempt {attempt}: Transaction status not ""yet available")else:raise# Wait before next attempt (except on last attempt)ifattempt<max_attempts:time.sleep(wait_seconds)print(f"\nTransaction not confirmed after {max_attempts} attempts")raiseRuntimeError(f"Transaction {transaction_hash} not confirmed in time")# Monitor the transaction until it's confirmedwait_for_transaction_confirmation(transaction_hash)
// ConfigurationconstNODE_URL=process.env.NODE_URL||'https://reference.symboltest.net:3001';console.log('Using node',NODE_URL);// Transaction hash to monitor.consttransactionHash=process.env.TRANSACTION_HASH||'2B6D3B5232E06B9D32682F518C765301FCF9716BFA1EEEF9523653406E04C7EA';console.log(`Monitoring transaction: ${transactionHash}`);/** * Poll the transaction status endpoint until it is confirmed. * @param {string} txHash - The hash of the transaction to monitor * @param {number} maxAttempts - Maximum number of polling attempts * for confirmation * @param {number} waitSeconds - Seconds to wait between attempts * @returns {boolean} True if transaction was confirmed */asyncfunctionwaitForTransactionConfirmation(txHash,maxAttempts=60,waitSeconds=2){conststatusPath=`/transactionStatus/${txHash}`;console.log('\nWaiting for transaction confirmation');console.log(`Polling ${statusPath}`);for(letattempt=1;attempt<=maxAttempts;attempt++){try{// Query the transaction status endpointconststatusResponse=awaitfetch(`${NODE_URL}${statusPath}`);if(!statusResponse.ok){conststatus=statusResponse.status;conststatusText=statusResponse.statusText;consterror=newError(`HTTP ${status}: ${statusText}`);error.status=statusResponse.status;throwerror;}conststatusJSON=awaitstatusResponse.json();// Parse the responseconststatusGroup=statusJSON.group;conststatusCode=statusJSON.code;conststatusHash=statusJSON.hash;conststatusDeadline=statusJSON.deadline;console.log(` Attempt ${attempt}:`);console.log(` Status: ${statusGroup}`);console.log(` Code: ${statusCode}`);console.log(` Hash: ${statusHash}`);console.log(` Deadline: ${statusDeadline}`);// Check if the transaction has been confirmedif('confirmed'===statusGroup){console.log('\nTransaction confirmed!');returntrue;}// Check if the transaction failedif('failed'===statusGroup){console.log(`\nTransaction failed with code: ${statusCode}`);thrownewError(`Transaction failed: ${statusCode}`);}}catch(error){if(404===error.status){console.log(` Attempt ${attempt}: Transaction status not yet `+'available');}else{throwerror;}}// Wait before next attempt (except on last attempt)if(attempt<maxAttempts){awaitnewPromise(resolve=>{setTimeout(resolve,waitSeconds*1000);});}}console.log(`\nTransaction not confirmed after ${maxAttempts} attempts`);thrownewError(`Transaction ${txHash} not confirmed in time`);}// Monitor the transaction until it's confirmedawaitwaitForTransactionConfirmation(transactionHash);
//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;importcom.fasterxml.jackson.databind.JsonNode;importcom.fasterxml.jackson.databind.ObjectMapper;// ConfigurationpublicfinalclassMonitoringStatus{privatestaticfinalObjectMapperJSON_MAPPER=newObjectMapper();privatestaticfinalHttpClientHTTP_CLIENT=HttpClient.newHttpClient();privatestaticfinalStringNODE_URL=System.getenv().getOrDefault("NODE_URL","https://reference.symboltest.net:3001");publicstaticvoidmain(finalString[]args){try{newMonitoringStatus().run();}catch(finalExceptionex){System.out.println(null==ex.getMessage()?ex.toString():ex.getMessage());}}privatevoidrun()throwsIOException,InterruptedException{System.out.printf("Using node %s%n",NODE_URL);// Transaction hash to monitor.finalStringtransactionHash=System.getenv().getOrDefault("TRANSACTION_HASH","2B6D3B5232E06B9D32682F518C765301FCF9716BFA1EEEF95236534"+"06E04C7EA");System.out.printf("Monitoring transaction: %s%n",transactionHash);// Monitor the transaction until it's confirmedwaitForTransactionConfirmation(transactionHash,60,2);}/** * Poll the transaction status endpoint until it is confirmed. * @param txHash The hash of the transaction to monitor * @param maxAttempts Maximum number of polling attempts * for confirmation * @param waitSeconds Seconds to wait between attempts * @return True if transaction was confirmed */privatebooleanwaitForTransactionConfirmation(finalStringtxHash,finalintmaxAttempts,finalintwaitSeconds)throwsIOException,InterruptedException{finalStringstatusPath="/transactionStatus/"+txHash;System.out.println("\nWaiting for transaction confirmation");System.out.printf("Polling %s%n",statusPath);for(intattempt=1;attempt<=maxAttempts;++attempt){// Query the transaction status endpointfinalHttpRequeststatusRequest=HttpRequest.newBuilder(URI.create(NODE_URL+statusPath)).GET().build();finalHttpResponse<String>statusResponse=HTTP_CLIENT.send(statusRequest,BodyHandlers.ofString());if(404==statusResponse.statusCode()){System.out.printf(" Attempt %d: Transaction status not yet available%n",attempt);}else{if(statusResponse.statusCode()/100!=2)thrownewIOException("HTTP "+statusResponse.statusCode());finalJsonNodestatusJSON=JSON_MAPPER.readTree(statusResponse.body());// Parse the responsefinalStringstatusGroup=statusJSON.get("group").asText();finalStringstatusCode=statusJSON.get("code").asText();finalStringstatusHash=statusJSON.get("hash").asText();finalStringstatusDeadline=statusJSON.get("deadline").asText();System.out.printf(" Attempt %d:%n",attempt);System.out.printf(" Status: %s%n",statusGroup);System.out.printf(" Code: %s%n",statusCode);System.out.printf(" Hash: %s%n",statusHash);System.out.printf(" Deadline: %s%n",statusDeadline);// Check if the transaction has been confirmedif("confirmed".equals(statusGroup)){System.out.println("\nTransaction confirmed!");returntrue;}// Check if the transaction failedif("failed".equals(statusGroup)){System.out.printf("%nTransaction failed with code: %s%n",statusCode);thrownewIOException("Transaction failed: "+statusCode);}}// Wait before next attempt (except on last attempt)if(attempt<maxAttempts)Thread.sleep(waitSeconds*1000L);}System.out.printf("%nTransaction not confirmed after %d attempts%n",maxAttempts);thrownewIOException("Transaction "+txHash+" not confirmed in time");}}
defwait_for_transaction_confirmation(tx_hash,max_attempts=60,wait_seconds=2):""" Poll the transaction status endpoint until the transaction is confirmed. Args: tx_hash: The hash of the transaction to monitor max_attempts: Maximum number of polling attempts for confirmation wait_seconds: Seconds to wait between attempts Returns: True if transaction was confirmed """status_path=f"/transactionStatus/{tx_hash}"print("\nWaiting for transaction confirmation")print(f"Polling {status_path}")forattemptinrange(1,max_attempts+1):try:# Query the transaction status endpointurl=f"{NODE_URL}{status_path}"withurllib.request.urlopen(url)asresponse:response_json=json.loads(response.read().decode())# Parse the responsestatus_group=response_json["group"]status_code=response_json["code"]status_hash=response_json["hash"]status_deadline=response_json["deadline"]print(f" Attempt {attempt}:")print(f" Status: {status_group}")print(f" Code: {status_code}")print(f" Hash: {status_hash}")print(f" Deadline: {status_deadline}")
/** * Poll the transaction status endpoint until it is confirmed. * @param {string} txHash - The hash of the transaction to monitor * @param {number} maxAttempts - Maximum number of polling attempts * for confirmation * @param {number} waitSeconds - Seconds to wait between attempts * @returns {boolean} True if transaction was confirmed */asyncfunctionwaitForTransactionConfirmation(txHash,maxAttempts=60,waitSeconds=2){conststatusPath=`/transactionStatus/${txHash}`;console.log('\nWaiting for transaction confirmation');console.log(`Polling ${statusPath}`);for(letattempt=1;attempt<=maxAttempts;attempt++){try{// Query the transaction status endpointconststatusResponse=awaitfetch(`${NODE_URL}${statusPath}`);if(!statusResponse.ok){conststatus=statusResponse.status;conststatusText=statusResponse.statusText;consterror=newError(`HTTP ${status}: ${statusText}`);error.status=statusResponse.status;throwerror;}conststatusJSON=awaitstatusResponse.json();// Parse the responseconststatusGroup=statusJSON.group;conststatusCode=statusJSON.code;conststatusHash=statusJSON.hash;conststatusDeadline=statusJSON.deadline;console.log(` Attempt ${attempt}:`);console.log(` Status: ${statusGroup}`);console.log(` Code: ${statusCode}`);console.log(` Hash: ${statusHash}`);console.log(` Deadline: ${statusDeadline}`);
/** * Poll the transaction status endpoint until it is confirmed. * @param txHash The hash of the transaction to monitor * @param maxAttempts Maximum number of polling attempts * for confirmation * @param waitSeconds Seconds to wait between attempts * @return True if transaction was confirmed */privatebooleanwaitForTransactionConfirmation(finalStringtxHash,finalintmaxAttempts,finalintwaitSeconds)throwsIOException,InterruptedException{finalStringstatusPath="/transactionStatus/"+txHash;System.out.println("\nWaiting for transaction confirmation");System.out.printf("Polling %s%n",statusPath);for(intattempt=1;attempt<=maxAttempts;++attempt){// Query the transaction status endpointfinalHttpRequeststatusRequest=HttpRequest.newBuilder(URI.create(NODE_URL+statusPath)).GET().build();finalHttpResponse<String>statusResponse=HTTP_CLIENT.send(statusRequest,BodyHandlers.ofString());if(404==statusResponse.statusCode()){System.out.printf(" Attempt %d: Transaction status not yet available%n",attempt);}else{if(statusResponse.statusCode()/100!=2)thrownewIOException("HTTP "+statusResponse.statusCode());finalJsonNodestatusJSON=JSON_MAPPER.readTree(statusResponse.body());// Parse the responsefinalStringstatusGroup=statusJSON.get("group").asText();finalStringstatusCode=statusJSON.get("code").asText();finalStringstatusHash=statusJSON.get("hash").asText();finalStringstatusDeadline=statusJSON.get("deadline").asText();System.out.printf(" Attempt %d:%n",attempt);System.out.printf(" Status: %s%n",statusGroup);System.out.printf(" Code: %s%n",statusCode);System.out.printf(" Hash: %s%n",statusHash);System.out.printf(" Deadline: %s%n",statusDeadline);
関数は、このチュートリアルの中核です。
トランザクションが承認されるか失敗するまで監視します。
for ループを使用して、デフォルトで最大60回(2秒間隔で2分間)トランザクションのステータスを確認します。
このループ構造により、トランザクションが承認されなかった場合でも、最終的には監視が停止することが保証されます。
# Check if the transaction failedifstatus_group=="failed":print(f"\nTransaction failed with code: {status_code}")raiseRuntimeError(f"Transaction failed: {status_code}")
// Check if the transaction failedif('failed'===statusGroup){console.log(`\nTransaction failed with code: ${statusCode}`);thrownewError(`Transaction failed: ${statusCode}`);}
// Check if the transaction failedif("failed".equals(statusGroup)){System.out.printf("%nTransaction failed with code: %s%n",statusCode);thrownewIOException("Transaction failed: "+statusCode);}