PixBee Bot - Not just another HIVE Bot - part1

in HiveDevs19 days ago (edited)

edited with Versão em PORTUGUES
and sorry for my English mistakes and grammar...


Hi Hive Devs, Hope to find you well!

I think this is my first post here, so let me introduce myself.

I'm a Software Engineer, Scrum Master and PMI Project Manager that start programming computers 30 years ago, about 10 years old to get my PC more RAM and run Games.

Start Windows Development using VB and moved after to Delphi, then I got my first job on a small Internet Provider that allowed me to learn Web Development and little bit of Design, Photoshop and deep dive into internet related stuff.

Then on my second job, I worked with lot of diferentes languages, as C/C++ and even Assembly, programming Microwaves, Sound Systems and TVs.

After creating and working in different projects, from office automation, spreadsheets and databases, importing and exporting data and flow control and document approvals between desktop apps and internet apps, I started my own development team and after studding PMBok I found in Scrum a game change for project management.

So, I like old technologies and always try to catch up with new ones, no different with blockchain.

I'm here since Hive Fork and for a while I wanted to contribute to Hive Development, but considering myself kinda retired from development, I focused on my Travel Blog, a way that I found to understand more Hive Blockchain and about 1 week ago, things changed, I had to get back to the keyboard to start this idea that was buzzing in my head.

I think everything started on a discussion on #HiveBR discord channel, and started thinking on this project more and more.

Idea

The project scope is implement the Brazilian PIX into the HIVE blockchain.

Maybe lot of people outside Brazil isn't familiar with PIX, but long story short, it's enable users to send money btw accounts in fast and secure way. You don't need to wait hours or Monday morning to see the deposit on your account. Very helpful and become the main money transfer and payments system in Brazil.

Using Hive and this fast transfer and all work around to Buy and Sell Hive made me wonder how easy would be send HIVE to PIX account and no more waiting for others to develop this idea, I decided to start it by myself.

After all, even with few people that can use it today, maybe we can push it to new users, as everytime that I try to onboard someone to Hive, came that question:

  • Ok, but how do I withdraw this Hive to BRL?
  • Ow, you need an exchange account, convert HIVE into BTC, convert BTC into BRL and then send a PIX to your account. And be careful with your exchange passwords f2a bla bla bla

I think I loose that person on the second part of this explanation!

So, Let's try to K.I.S.S.!

Planning

To accomplish this project, I spend couple of days studying others Hive Projects, the HIVE API documentation and the HIVE-JS lib.

Yes, I believe it's possible and I think I can do it. I worked with Nodejs before but just a little bit... never a full project from scratch.

Async Functions and Await make me mad when things go wrong, so it's time to face it and let's do it.

I forked and study mainly two projects available on Github:

image.png

NPM INIT

image.png

and start... I was not sure about the project name yet, I came up with the name after writing a lot of PIX on my code, at first was just another "hivebot".

in a solo brain storm and lot of aweful names, like defi something defi pix or no pix at all, I was thinking in how to color the code and the yellow color on the screen was reminding me a working bee and... BeePix, but don't sound right, but PixBee...; something like "Pixbi" in pt-br sounds better, so the name was that.

Remember that on that moment, I run to create that account thinking it must be taken, but not, it was available a must register right now!

I could not get a free account, purchased the account with hive, it was not working and who saved me was 3speak.tv. fewwww the account is mine.

Show Prices

Now I can get back to work. At this moment, I could manage only to display the exchanges prices and calculate the average and VWAP based on pricefeed project. Helped a lot all that calculation.

image.png

The next step was to convert the Hive Price in BRL, we don't have it on exchanges, so, based on Dolar, Real and Hive prices, I started to store that value to further use.

Hive-JS

The hive-js part was cool to implement, I was reading the ali-h hive-bot code and rewriting it on my project. I didn't want just a working bot, I wanted to understand every part of it and how it works.

Can't work with finance project and don't know how the things run under my code. Also, I tried to use less libs as possible to make tasks done...

image.png

After a few tweaks on the code, I could connect to deatwing node and start listening to the blockchain. But I couldn't ready anything. It was displaying comments, new posts, votes and everything possible on observer mode. So I had to fix thinkgs up.

Starting to give it some color the identify comments and new posts and was very brz colors i confess, not intend.. but i liked the color code.

image.pngimage.pngimage.png

After color up and clean up the 'comments.body' to display only text and not all the markups, started to become more easy to read the screen.

So, now I can listen to HIVE but don't need it now, lets create some configs flags to process or not comments and new posts. I'll be using this latter on the project.

The issue was, not display anything on the screen, looks like my bot is dead, so I decided to enable to display only the the new posts until I had more stuff to display.

I'm Alive

image.png

I was programming this bot with the PixBee bee on my mind, and at this moment, i only had the price feed on the screen. looks totally borring.

We need to include some action here.

I decide to create a imAlive routine, so, after few minutes, we print the price feed again, and after, some statistics, prices, and util information.

Instead of running, my bot will fly!

image.png

TODO List

Ok, so It's quite done, right? tottaly wrong. I was feeling that more code i wrote, more code i had to write. lol

At this point, I was with the basic tools setup. I have the HIVE Price in USD BRL.

Now I 'just' need (retrieved from my readme.md todo list):

Get price from exchanges and display
Calculate Average price from exchanges

Setup Hive JS
Setup the Bot to Listen to Hive Blockchain
Handle New Posts from All Users

Bot Display some stats
Bot Display new posts link to favorite frontend

Include BTC HIVE BRL USDT prices

Handle New Transfers from All Users
Handle Transfers only from Target Account
Get Hive Account Information
Setup Webhooks

Get Bank Account Information
Get hive balance
Get pix balance

Tunnel to Internet
Create webhook to listen new Pix Transfers

Handle Hive Received on Target Account
Refund users if anything goes wrong.
If no memo specified? consider tip?

Calculate Fees. Need to earn some HIVE

implement sendPix(value)
refund Hive if Pix Error

Handle Pix Received on Bank Account
check if memo is valid hive account
check if hive account exist
calculate fees

sendHive(value)

Update Pix monitor webhook when bot start
Improve Bot Statitcs displayed

easy, Ill bring more updates on next post.

If you liked the idea, let me know, if you don't let me know too.

And thank you all hive devs from discord channel that help me out with my questions and doubts.

see you soon.

@pixbee




Versão Brasileira

Olá Hive Devs, espero que esteja bem!

Acho que este é meu primeiro post aqui, então vou me apresentar.

Sou Engenheiro de Software, Scrum Master e Gerente de Projetos do PMI que comecei a programar computadores há 30 anos, cerca de 10 anos, para ter mais RAM no meu PC e rodar jogos.

Comecei o Desenvolvimento Windows usando VB e depois mudei para Delphi, então consegui meu primeiro emprego em um pequeno provedor de Internet que me permitiu aprender Desenvolvimento Web e um pouco de Design, Photoshop e me aprofundar em assuntos relacionados à Internet.

Depois no meu segundo emprego, trabalhei com diversas linguagens, como C/C++ e até Assembly, programando Microondas, Sistemas de Som e TVs.

Depois de criar e trabalhar em diversos projetos, desde automação de escritório, planilhas e bancos de dados, importação e exportação de dados e controle de fluxo e aprovações de documentos entre aplicativos desktop e aplicativos de internet, montei minha própria equipe de desenvolvimento e após estudar PMBok encontrei no Scrum uma mudança para gerenciamento de projetos de forma ágil.

Então, gosto de tecnologias antigas e procuro sempre estar em dia com as novas, não é diferente com a blockchain.

Estou aqui desde o Hive Fork e há algum tempo queria contribuir com o Hive Development, mas estava meio que aposentado do desenvolvimento, foquei no meu Travel Blog, uma forma que encontrei para entender mais o Hive Blockchain, e há cerca de 1 semana, as coisas mudaram, tive que voltar ao teclado para dar início a essa ideia que pulsava na minha cabeça.

Acho que tudo começou em uma discussão no canal do discord #HiveBR, e comecei a pensar cada vez mais nesse projeto.

Ideia

O escopo do projeto é implementar o PIX brasileiro na blockchain HIVE.

Talvez muitas pessoas fora do Brasil não estejam familiarizadas com o PIX, mas, resumindo, ele permite que os usuários enviem dinheiro entre contas de maneira rápida e segura. Você não precisa esperar horas ou segunda-feira de manhã para ver o depósito em sua conta. Muito útil e se tornou o principal sistema de transferência e pagamentos de dinheiro do Brasil.

Usar o Hive e essa transferência rápida e todo o trabalho para Comprar e Vender Hive me fez pensar o quão fácil seria enviar o HIVE para a conta PIX e sem mais esperar que outros desenvolvessem essa ideia, decidi começar sozinho.

Afinal, mesmo com poucas pessoas que podem usá-lo hoje, talvez possamos divulgar para novos usuários, pois toda vez que tento integrar alguém ao Hive, surge aquela pergunta:

  • Ok, mas como faço para retirar esse Hive para BRL?
  • Ai, você precisa de uma conta exchange, converter HIVE em BTC, converter BTC em BRL e depois enviar um PIX para sua conta.
  • E tenha cuidado com suas senhas de troca f2a bla bla bla

Acho que perdi essa pessoa na segunda parte desta explicação!

Então, vamos tentar DEIXAR ISSO SIMPLES!

Planejamento

Para realizar este projeto, passei alguns dias estudando outros projetos Hive, a documentação da API HIVE e a biblioteca HIVE-JS.

Sim, acredito que é possível e acho que consigo... Já trabalhei com Nodejs antes, mas só um pouquinho... nunca um projeto completo do zero.

Funções Async e Await me deixam furioso quando as coisas dão errado, então é hora de encarar isso e vamos lá.

Fiz Fork de dois projetos disponíveis no Github para estudo:

image.png

NPM INIT

image.png

e começe... Ainda não tinha certeza do nome do projeto, criei o nome depois de escrever muito PIX no meu código, no começo era só mais um "hivebot".

em um brainstorm solo e muitos nomes horríveis, como defi algo defi pix ou outra coisa pix, eu estava pensando em como colorir o código e a cor amarela na tela me lembrou uma abelha trabalhadora e... BeePix, mas não parece certo, mas PixBee...; algo como "Pixbi" em pt-br soa melhor, então o nome era esse.

Lembre-se que naquele momento corri para criar aquela conta pensando que ela deveria ser tomada, mas não, ela estava disponível e é necessário cadastrar-se agora mesmo!

Não consegui uma conta gratuita, comprei a conta com hive, não estava funcionando e quem me salvou foi o 3speak.tv. ufaaaaa! a conta é minha.

Mostrar preços

Agora posso voltar ao trabalho. Neste momento, consegui apenas exibir os preços das exchanges e calcular a média e o VWAP com base no projeto pricefeed. Ajudou muito todo esse cálculo.

image.png

O próximo passo foi converter o Hive Price em BRL, não temos nas exchanges, então, com base nos preços em Dolar, Real e Hive, comecei a armazenar esse valor para uso posterior.

Hive-JS

A parte do hive-js foi legal de implementar, eu estava lendo o código do ali-h hive-bot e reescrevendo no meu projeto. Eu não queria apenas um bot funcional, queria entender cada parte dele e como funciona.

Não queria trabalhar com projeto financeiro e não saber como as coisas funcionam no meu código. Além disso, tentei usar menos bibliotecas possíveis para realizar as tarefas...

image.png

Depois de alguns ajustes no código, consegui me conectar ao nó deadwing e começar a ouvir a HIVE blockchain. Exibia comentários, novas postagens, votos e tudo o que era possível no modo observador. Então eu tive que alinhar os pensamentos.

Começando dando um pouco de cor nos comentários de identificação e nas novas postagens e ficou com cores bem BRASIL, confesso, não premeditado.. mas gostei do código de cores.

image.pngimage.pngimage.png

Depois de colorir e limpar o 'comments.body' para exibir apenas o texto e não todas as marcações, começou a ficar mais fácil de ler a tela.

Então, agora posso ouvir o HIVE, mas não preciso disso agora, vamos criar algumas flags de configuração para processar ou não comentários e novas postagens.

Um problema era não exibir nada na tela, parece que meu bot está travado, então decidi habilitar a exibição apenas dos novos posts até que tivesse mais coisas para exibir.

Estou Vivo!

image.png

Eu estava programando esse bot pensando na abelha PixBee e, nesse momento, só tinha o feed de preço na tela. parece totalmente emprestado.

Precisamos incluir alguma ação aqui.

Decido criar uma rotina imAlive, então, após alguns minutos, imprimimos novamente o tabela de preços e, em seguida, algumas estatísticas, preços e informações util.

Em vez de "running...", meu bot irá escrever "flying..."! (Voando por causa da abelha.)

image.png

Lista de afazeres

Ok, então está tudo pronto, certo? totalmente errado. Eu estava sentindo que mais código eu escrevia, mais código eu tinha que escrever. lol

Neste ponto, eu estava com a configuração das ferramentas básicas. Tenho o preço do HIVE em USD BRL.

Agora eu "só" preciso (recuperado da minha lista de tarefas readme.md):

Get price from exchanges and display
Calculate Average price from exchanges

Setup Hive JS
Setup the Bot to Listen to Hive Blockchain
Handle New Posts from All Users

Bot Display some stats
Bot Display new posts link to favorite frontend

Include BTC HIVE BRL USDT prices

Handle New Transfers from All Users
Handle Transfers only from Target Account
Get Hive Account Information
Setup Webhooks

Get Bank Account Information
Get hive balance
Get pix balance

Tunnel to Internet
Create webhook to listen new Pix Transfers

Handle Hive Received on Target Account
Refund users if anything goes wrong.
If no memo specified? consider tip?

Calculate Fees. Need to earn some HIVE

implement sendPix(value)
refund Hive if Pix Error

Handle Pix Received on Bank Account
check if memo is valid hive account
check if hive account exist
calculate fees

sendHive(value)

Update Pix monitor webhook when bot start
Improve Bot Statitcs displayed

fácil, trarei mais atualizações no próximo post.

Se gostou da ideia me avise, se não me avise também.

E obrigado a todos os desenvolvedores do canal discord que me ajudam com minhas dúvidas.

nos vemos em breve.

@pixbee




Sort:  

This is a hive-archeology proxy comment meant as a proxy for upvoting good content that is past it's initial pay-out window.

image.png

Pay-out for this comment is configured as followed:

roleaccountpercentagenote
curator-0.0%curation rewards disabled
dev@croupierbot2.5%author of hive-archology
dev@emrebeyler2.5%author of lighthive
author@vaipraonde95.0%

This is new?!!!
Never see it around here.

Tks for the support

Obrigado por promover a comunidade Hive-BR em suas postagens.

Vamos seguir fortalecendo a Hive

Metade das recompensas dessa resposta serão destinadas ao autor do post.

Vote no @perfilbrasil para Testemunha Hive.

Legal te ver empenhado em um projeto novamente. Parabéns.

Valeu pelo suporte!

Da hora mano, espero que de certo, vai ser bem interessante esse sistema. Trocar o hive direto e receber um pix na hora, sem ter que fazer tudo por corretoras sera uma grande economia de tempo e ajuda para os novatos!

!LOLZ !PIMP !PGM


You must be killin' it out here!
@shiftrox just slapped you with 1.000 PIMP, @vaipraonde.
You earned 1.000 PIMP for the strong hand.
They're getting a workout and slapped 1/1 possible people today.

pimp_logo


Read about some PIMP Shit or Look for the PIMP District

What's the difference between a cat and a frog?
A cat has nine lives, but a frogs croaks every night.

Credit: reddit
@vaipraonde, I sent you an $LOLZ on behalf of shiftrox

(2/10)
Farm LOLZ tokens when you Delegate Hive or Hive Tokens.
Click to delegate: 10 - 20 - 50 - 100 HP

valeu! estou empenhado em fazer funcionar.
e não somente isso, se tudo der certo, voce podera fazer um pix ate para terceiros direto da sua wallet do hive

Parabéns pela ideia e iniciativa! Segundo essa matéria na Argentina, EUA, Paraguai e Uruguai já aceitam Pix por causa dos turistas brasileiros: https://www.infomoney.com.br/minhas-financas/consumidor-brasileiro-pode-usar-pix-nos-eua-argentina-e-uruguai-diz-campos-neto/ De repente, se o Pix internacionalizar mesmo o bot pode virar alternativa para outros países com moedas não tão fortes como a nossa. Valeu! Saúde, sucesso e boa sorte mais uma vez!

Que legal essa informacao, ainda nao sabia e ate coloquei algumas coisas relacionadas a America Latina, mas isso mesmo, ja pensando em uma evolucao. porque hoje mesmo brz ativos nao sao muitos.

se quiser me ajudar, fiz uma "pesquisa de mercado" para a #HiveBr

https://forms.gle/h9woeYY3jKrJk7QDA

abs

Respondi lá, valeu! Inclui o link pra esse post lá na pg sobre a Hive na comunidade da Confraria Web3 tb: https://lms.confrariaweb3.com.br/posts/53371441?utm_source=manual Se quiser conferir mas ainda não é membro do site da comunidade, segue o link de cadastro: https://lms.confrariaweb3.com.br/share/GjqsWajNIY93jAYz?utm_source=manual (referral que me recompensa como perfil que indicou). Valeu!

Estou por la sim! valeu pelo suporte!

Se quiser entrar para o Beta Test do Pixbee me avisa!

saiu part 2 @vaipraonde/pixbee-bot-not-just-another-hive-bot-part2

abracos

!hbit

@vaipraonde mined HBIT. ⛏️ (1/1) tools | trade | connect

Made with LUV by crrdlx.