File Coverage

blib/lib/CryptoTron/JsonHttp.pm
Criterion Covered Total %
statement 26 81 32.1
branch 0 24 0.0
condition 0 6 0.0
subroutine 9 14 64.2
pod 0 5 0.0
total 35 130 26.9


line stmt bran cond sub pod time code
1              
2             # Load the Perl pragmas.
3             use 5.008008;
4 1     1   17 use strict;
  1         4  
5 1     1   5 use warnings;
  1         2  
  1         20  
6 1     1   15  
  1         2  
  1         41  
7             # Load the Perl pragma Exporter.
8             use vars qw(@ISA @EXPORT @EXPORT_OK);
9 1     1   5 use Exporter 'import';
  1         1  
  1         64  
10 1     1   6  
  1         2  
  1         85  
11             # Base class of this (tron_addr) module.
12             our @ISA = qw(Exporter);
13              
14             # Exporting the implemented subroutine.
15             our @EXPORT = qw(
16             HTTP_Request
17             encode_data
18             json_data
19             format_output
20             payload_standard
21             %SERVICES
22             $API_URL
23             );
24              
25             # Set the package version.
26             our $VERSION = '0.13';
27              
28             # Load the required Perl modules or packages.
29             use JSON::PP;
30 1     1   875 use URI;
  1         20201  
  1         72  
31 1     1   648 use LWP::UserAgent;
  1         5667  
  1         30  
32 1     1   682  
  1         47873  
  1         38  
33             # Load the required modules.
34             use CryptoTron::AddressCheck;
35 1     1   527  
  1         307264  
  1         876  
36             # Set api url and api path.
37             our $API_URL = 'https://api.trongrid.io';
38              
39             # Define the hash with the services.
40             our %SERVICES = (
41             'GetNextMaintenanceTime' => ['/wallet/getnextmaintenancetime', 'GET'],
42             'BroadcastTransaction' => ['/wallet/broadcasttransaction', 'POST'],
43             'FreezeBalance' => ['/wallet/freezebalance', 'POST'],
44             'GetAccount' => ['/walletsolidity/getaccount', 'POST'],
45             'GetBrokerage' => ['/wallet/getBrokerage', 'POST'],
46             'GetAccountBalance' => ['/wallet/getaccountbalance', 'POST'],
47             'GetAccountNet' => ['/wallet/getaccountnet', 'POST'],
48             'GetAccountResource' => ['/wallet/getaccountresource', 'POST'],
49             'GetReward' => ['/wallet/getReward', 'POST'],
50             'UnfreezeBalance' => ['/wallet/unfreezebalance', 'POST'],
51             'WithdrawBalance' => ['/wallet/withdrawbalance', 'POST']
52             );
53              
54             # Configure a new JSON:PP object.
55             our $indent_enable = "true";
56             our $indent_spaces = 4;
57             our $JSON;
58             $JSON = 'JSON::PP'->new->pretty;
59             $JSON = $JSON->indent($indent_enable);
60             $JSON = $JSON->indent_length($indent_spaces);
61             $JSON = $JSON->allow_unknown("true");
62             $JSON = $JSON->allow_blessed("true");
63             $JSON = $JSON->allow_singlequote("true");
64              
65             # ---------------------------------------------------------------------------- #
66             # Subroutine payload_standard() #
67             # ---------------------------------------------------------------------------- #
68             # Assign the subroutine arguments to the local array.
69             my ($args) = @_;
70             # Set the local variables.
71 0     0 0   my $addr = $args->{PublicKey};
72             my $flag = $args->{VisibleFlag};
73 0           my $chk = $args->{ControlFlag};
74 0           # Check if the the local variables are defined.
75 0           $addr = (defined $addr ? $addr : "");
76             $chk = (defined $chk ? $chk : "True");
77 0 0         $flag = (defined $flag ? $flag : "True");
78 0 0         # Initialise the local variable $payload.
79 0 0         my $payload = "";
80             # Check if the $address is not empty.
81 0           if ($addr ne "") {
82             if ($chk eq "True") {
83 0 0         # Check variable $visible.
84 0 0         my $isBase58Addr = ($flag eq "True" && chk_base58_addr($addr) != 1);
85             my $isHexAddr = ($flag eq "False" && chk_hex_addr($addr) != 1);
86 0   0       $flag = ($isBase58Addr ? "False" : "True");
87 0   0       $flag = ($isHexAddr ? "True" : "False");
88 0 0         };
89 0 0         # Create the payload from the address.
90             $payload = "\{\"address\":\"${addr}\",\"visible\":\"${flag}\"\}";
91             };
92 0           # Return the payload string.
93             return $payload;
94             };
95 0            
96             # ---------------------------------------------------------------------------- #
97             # Subroutine json_data() #
98             # ---------------------------------------------------------------------------- #
99             # Assign the arguments to the local array.
100             my ($args) = @_;
101             # Set the local variables.
102             my $outfmt = (defined $args->{OutputFormat} ? $args->{OutputFormat} : "RAW");
103 0     0 0   # Get the name of the calling module.
104             my $module_name = $args->{ModuleName};
105 0 0         # Get the payload string.
106             my $payload = $args->{PayloadString};
107 0           # Get service url and related method.
108             my $service_url = $API_URL.$SERVICES{$module_name}[0];
109 0           my $method = $SERVICES{$module_name}[1];
110             my $content = "";
111 0           # Initialise the return variable.
112 0           my $output_data = "{}";
113 0           # Get the content from the service url.
114             ($content, undef, undef, undef) = HTTP_Request($service_url, $method, $payload);
115 0           # Format the content for the output.
116             $output_data = format_output($content, $outfmt);
117 0           # Return the JSON data raw or formatted.
118             return $output_data;
119 0           };
120              
121 0           # ---------------------------------------------------------------------------- #
122             # Subroutine format_output() #
123             # ---------------------------------------------------------------------------- #
124             # Assign the subroutine arguments to the local variables.
125             my ($content, $outflag) = @_;
126             # Declare the return variable.
127             my $output;
128             # Format the content for the output.
129 0     0 0   if ($outflag eq "RAW") {
130             # Use the content as it is.
131 0           $output = $content;
132             } else {
133 0 0         # Encode the content.
134             $output = encode_data($content);
135 0           };
136             # Return formatted output.
137             return $output;
138 0           };
139             # ---------------------------------------------------------------------------- #
140             # Subroutine encode_data() #
141 0           # #
142             # Description: #
143             # At first glance, it is not obvious why the response should be decoded and #
144             # then encoded back again. However, if one assumes that the response can have #
145             # any structure, this procedure makes sense. Decoding creates a Perl data #
146             # structure from the response. Encoding then creates a formatted string from #
147             # the Perl data structure. #
148             # #
149             # @argument $content Content from response (scalar) #
150             # @return $encoded Encoded formatted content (scalar) #
151             # ---------------------------------------------------------------------------- #
152             # Assign the subroutine argument to the local variable.
153             my $content = $_[0];
154             # Decode the content of the response using 'JSON:PP'.
155             my $decoded = $JSON->decode($content);
156             # Encode the content of the response using 'JSON:PP'.
157             my $encoded = $JSON->encode($decoded);
158 0     0 0   # Return the encoded formatted JSON content.
159             return $encoded;
160 0           };
161              
162 0           # ---------------------------------------------------------------------------- #
163             # Subroutine HTTP_Request() #
164 0           # #
165             # Description: #
166             # The subroutine is using the HTTP methods GET or POST to send a request to a #
167             # known servive url of the FULL-NODE HTTP API. On success a content in form of #
168             # JSON data is returned. #
169             # #
170             # @argument $service_url Service url (scalar) #
171             # @return $content Response content (scalar) #
172             # ---------------------------------------------------------------------------- #
173             # Assign the subroutine arguments to the local variables.
174             my ($service_url, $method, $payload) = @_;
175             # Initialise the local variables.
176             my $content = "";
177             my $response = "";
178             my $errcode = "";
179             my $errmsg = "";
180 0     0 0   # Create a new uri object from the service url.
181             my $uri = URI->new($service_url);
182 0           # Create a new user agent object.
183 0           my $ua = LWP::UserAgent->new();
184 0           # Set the default header of the request.
185 0           $ua->default_header('Accept' => 'application/json');
186             $ua->default_header('Content_Type' => 'application/json');
187 0           # Get the response from the uri based on the given HTTP method.
188             if ($method eq 'POST') {
189 0           $response = $ua->post($uri, 'Content' => $payload);
190             } elsif ($method eq 'GET') {
191 0           $response = $ua->get($uri, 'Content' => $payload);
192 0           };
193             # Get error code and error message.
194 0 0         $errcode = $response->code;
    0          
195 0           $errmsg = $response->message;
196             # Check success of operation.
197 0           if ($response->is_success) {
198             # Get the content from the response.
199             $content = $response->content;
200 0           } else {
201 0           # Set the content to an empty string.
202             $content = "";
203 0 0         };
204             # Return content, error code, error message and service url.
205 0           return ($content, $errcode, $errmsg, $service_url);
206             };
207              
208 0           1;
209              
210              
211 0           =head1 NAME
212              
213             CryptoTron::JsonHttp - Perl extension for use with the blockchain of the crypto coin Tron.
214              
215             =head1 SYNOPSIS
216              
217             None
218              
219             =head1 DESCRIPTION
220              
221             None
222              
223             =head1 SEE ALSO
224              
225             Try::Catch
226              
227             POSIX
228              
229             URI
230              
231             LWP::UserAgent
232              
233             JSON::PP
234              
235             =head1 AUTHOR
236              
237             Dr. Peter Netz, E<lt>ztenretep@cpan.orgE<gt>
238              
239             =head1 COPYRIGHT AND LICENSE
240              
241             Copyright (C) 2022 by Dr. Peter Netz
242              
243             The MIT License
244            
245             Permission is hereby granted, free of charge, to any person
246             obtaining a copy of this software and associated
247             documentation files (the "Software"), to deal in the Software
248             without restriction, including without limitation the rights to
249             use, copy, modify, merge, publish, distribute, sublicense,
250             and/or sell copies of the Software, and to permit persons to
251             whom the Software is furnished to do so, subject to the
252             following conditions:
253            
254             The above copyright notice and this permission notice shall
255             be included in all copies or substantial portions of the
256             Software.
257            
258             THE SOFTWARE IS PROVIDED "AS IS", WITHOUT
259             WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
260             INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
261             MERCHANTABILITY, FITNESS FOR A PARTICULAR
262             PURPOSE AND NONINFRINGEMENT. IN NO EVENT
263             SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
264             LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
265             LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
266             TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
267             CONNECTION WITH THE SOFTWARE OR THE USE OR
268             OTHER DEALINGS IN THE SOFTWARE.
269              
270             =cut