Finance-Dogecoin

 view release on metacpan or  search on metacpan

lib/Finance/Dogecoin/API.pm  view on Meta::CPAN

package Finance::Dogecoin::API;
$Finance::Dogecoin::API::VERSION = '1.20140201.1608';
use 5.010;

use Moo;
# limit the damage from Moo's use of strictures
# see: http://www.modernperlbooks.com/mt/2014/01/fatal-warnings-are-a-ticking-time-bomb.html
use warnings NONFATAL => 'all';

use Carp ();

use URI;
use JSON;
use HTTP::Headers;
use LWP::UserAgent;
use LWP::Protocol::https;
use URI::QueryParam;

has 'api_key',  is => 'ro', required => 1;
has 'endpoint', is => 'ro', default  => sub { 'https://www.dogeapi.com/wow/' };
has 'json',     is => 'ro', default  => sub {
    my $j = JSON->new; $j->allow_nonref; $j
};

has 'ua',       is => 'ro', default => sub {
    my $headers = HTTP::Headers->new;
    $headers->header( 'Content-Type' => 'application/json' );
    LWP::UserAgent->new(
        ssl_opts        => { verify_hostname => 1 },
        default_headers => $headers,
    );
};

sub request {
    my ($self, $method, %params) = @_;

    # manually setting the 'a' parameter avoids a weird behavior in LWP::UA
    # which uppercases 'a'--not what the API expects or wants
    my $uri = URI->new( $self->endpoint );
    $uri->query_param( a => $method );

    while (my ($key, $value) = each %params) {
        $uri->query_param( $key => $value );
    }

    my $response = $self->ua->get( $uri );
    my $result   = $self->json->decode( $response->decoded_content );

    Carp::croak( "Bad API call from $method() call" ) if $result eq 'Bad Query';
    Carp::croak( "Invalid API key '" . $self->api_key . "'" )
        if $result eq 'Invalid API Key';

    return $result;
}

BEGIN {
    for my $non_api (qw( get_difficulty get_current_block get_current_price )) {
        my $method = sub { $_[0]->request( $non_api ) };
        do {
            no strict 'refs';
            *{ $non_api } = $method;
        };
    }

    for my $api (qw( get_balance get_my_addresses )) {
        my $method = sub { $_[0]->request( $api, api_key => $_[0]->api_key ) };
        do {
            no strict 'refs';
            *{ $api } = $method;
        };
    }
}

sub withdraw {
    my ($self, %params) = @_;

    my @errors;

    for my $param (qw( payment_address amount )) {
        push @errors, $param unless $params{$param};
    }

    if (@errors) {
        my $error = join ', ', @errors;
        Carp::croak( "Must call withdraw() with $error params" );
    }

    Carp::croak( 'Must call withdraw() with amount of at least 5 Doge' )
        if $params{amount} < 5;

    $self->request( 'withdraw', api_key => $self->api_key, %params );
}

sub get_new_address {
    my ($self, %params) = @_;
    $self->request( 'get_new_address', api_key => $self->api_key, %params );
}

sub get_address_received {



( run in 1.174 second using v1.01-cache-2.11-cpan-39bf76dae61 )