PixBee Bot - Not just another HIVE Bot - part2

in HiveDevs17 days ago

Wrote in English and translated to Portugues Brasil using GT. Sorry for any grammar mistakes


Hi HiveDevs friends! how are you doing this weekend?

Continuing PixBee Bot - Not just another HIVE Bot - part1...

This post I'll show how PixBee handle Deposits and few situations that came up during the script.


At this moment, PixBee managed to startup the bot to fetch exchanges API, calculate HIVE average prices in BRL and USD and observing the HIVE blockchain for new transfers, new posts and new comments, while logging this data on the screen to show some motion to be aware that the app is working and 'flying'.

Now, as next steps PixBee need to:

Handle Transfers from PixBee Accounts
Get Bank Account balance
Get HIVE account balance
Get PIX account balance
Webhook Endpoint to receive Pix Transfers notification

To handle new transfers on the blockchain, I came up with an idea that was to listen 2 exchanges accounts, this way, PixBee can get some data in a short period of time, because if listen to the new created PixBee account, It will not have any data to test and the need to create some transactions on the Hive mainnet. And working with some real data is much better.

Here's the deal, each time PixBee identify a HIVE transfer we are going to log on the screen:

  • HIVE Received
  • Convert HIVE to BRL
  • Display on the screen
  • Start a handleTransferHive(data);

And after few lines of code...

Yeah! It's working!

I'm using CoinStats app converter to check the values and conversion. And it's very similar, just few cents of difference due the exchange prices and my average price, but this way I made sure calculus is correct.

Receiving PIX

Before staring handling Hive transactions, I went to the PIX handling, so I created a Endpoint to receive PIX received notifications and log on the screen.

Using the Bank API sandbox I created a new pix received event, that triggered PixBee endpoint and could receive it with no issues.

image.png

Receiving Hive

I noticed that lot of the values received from that exchange, was too high (for me at least) so, came up with the idea to include some exchanges limits until I have enough funds to make that transaction possible.

I want to make it flexible, so 1 user can purchase or sell the whole amount available instead have to limit, but another upcoming feature. Only counties has limits, right?

Limits do we need it?

So, I set two limits, the minimum and the maximum. And a Fee for using the service and do not respect the min and max deposits amounts. Initially set as 7% but maybe it´s to high, not sure, not thinking in tax right now. PixBee can change it easily just setup a new value for that var and we can take advantage of that to create promotions periods, increase or decrease tax easily.

So far we have this values:

LimitsValue
MinimumR$ 50
MaximumR$ 200
Service Fee7%
Service Fee2%
Fixed FeeR$ 2

And with that, now PixBee can handle Out Of Limits errors. Nice!

Out of Limits, value too high

Sending HIVE

A critical event to handle now, to be able to send HIVE, PixBee is going to need a valid Active Key and any code mistake can let PixBee to run out funds. At this moment I tried to use HIVE Testnet, but found out that it's not available yet.

I need to create my own Hive Testnet to be able to test it without sending my PixBee HIVE.

With no Testnet available, I decided to handle this way. PixBee will create the transfer object but will not broadcast it to Hive mainnet. only Log on the screen the transfer data.

image.png

I tried to use some color codes to identify easily what kind of transaction was being received, Green for Hive Received, Red for Errors and Blue to transactions.

Refunding Process

Looks like the process is almost done, we can Receive PIX and ready to send HIVE, we Can Receive Hive and maybe need a Refund, let´s try the process.

Receive Hive or PIX and handle it with the possibility to handles errors in the middle.

Now the key is to broadcast the information to Hive that I will not test it yet. The code is done, but the flag to only log transfer of the object I'll not broadcast it. And looks like it's good to go.

image.png

image.png

image.png

Pix Keys Types

For everyone who is not used to the Pix key, it can have 4 types:

CPFpersonal registration number999.999.999-99
Cell phone(99)99999-9999
Email[email protected]
CNPJregistration number for companies99.999.999/9999-99
EVPUnique key generated by Brazilian Central Bankxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

At first, I choose only to accept the Random key as parameter to handle the PIX transfers, but the most common types used is Cell phone or CPF, and for CNPJ. I'm not sure if people will want to have some personal data as CPF registered on the blockchain, but... let let it as upcoming feature.

Now we need to grab the HIVE MEMO description and handle it to get the PIX Key.

To make that possible, I create another script config flag to test transfer, and on that case, replace the MEMO with a valid EVP KEY.

This way I could test for wrong EVP key formats and right EVP formats with minimum modification on my code, just setting up a flag.

Validating EVP Key

After storing all received information as user, key, hive amount and the converted BRL value, if any error occurs on the next transactions, PixBee can manage to refund it to the user with no effort.

And it worked like a charm. Each time PixBee received a wrong EVP KEY (all of the transactions so far) PixBee could refund the user right away.

Transfers with no Memo Key

As I was targeting two accounts to receive test data, one of them Receive all HIVE with no MEMO key. At first, I thought that could be a user error when transferring it to PixBee and the PixBee bot will identify it as error and refund the user immediately.

But after some transactions, something come in my mind. How users can TIP the service or if PixBee bot need to receive some amount that is not to PIX transfer?

The solution was implementing a 'TIP Honey Pot', and if the user really made a mistake, it will need to Open a Ticket to retrieve this amount manually.

I think PixBee need an assistant to handle this Tickets issues. maybe a WhatsApp support channel connected with AI to handle this kind of tickets.

Yeah!

No Balance?

As PixBee still isn't handling accounts low balance, I think is the next step to setup. I'll need to get PixBee Hive account balance and my PIX account balance so PixBee can know if it complete the transaction before even starting it.

It's a good moment for reflection, pause and sprucing up the codes.

You are seeing colorful screen shots, but in the beginning, it was codes and more codes that was hard to read all those codes even for me that was creating it.

Took some time to improve and refactoring some codes and prettify the logs. Further I want to make it simple, like just one line so I don't get too much screen scrolling.

More I code, more the TODO list increase, lol

image.png




Versão Brasileira

Olá amigos HiveDevs! Como você está neste fim de semana?

Continuando PixBee Bot - Not just another HIVE Bot - part1...

Neste post vou mostrar como o PixBee lida com os Depósitos e algumas situações que surgiram durante o roteiro.


Neste momento, PixBee conseguiu inicializar o bot para buscar a API das exchanges, calcular os preços médios do HIVE em BRL e USD e observar o blockchain do HIVE para novas transferências, novos posts e novos comentários, enquanto registrava esses dados na tela para mostrar algum movimento para esteja ciente de que o aplicativo está funcionando e 'voando'.

Agora, como próximos passos o PixBee precisa:

Handle Transfers from PixBee Accounts
Get Bank Account balance
Get HIVE account balance
Get PIX account balance
Webhook Endpoint to receive Pix Transfers notification

Para lidar com novas transferências no blockchain, tive uma ideia que era ouvir 2 contas de exchanges, desta forma, o PixBee consegue obter alguns dados em um curto período de tempo, pois se ouvir a nova conta PixBee criada, não irá tem algum dado para testar e a necessidade de criar algumas transações na rede principal do Hive. E trabalhar com alguns dados reais é muito melhor.

O negócio é o seguinte: cada vez que o PixBee identificar uma transferência HIVE iremos fazer login na tela:

  • HIVE Received
  • Convert HIVE to BRL
  • Display on the screen
  • Start a handleTransferHive(data);

E depois de algumas linhas de código...

Yeah! It's working!

Estou usando o conversor do aplicativo CoinStats para verificar os valores e a conversão. E é muito parecido, apenas alguns centavos de diferença devido aos preços de câmbio e ao meu preço médio, mas assim garanti que o cálculo está correto.

Recebendo PIX

Antes de começar a tratar as transações do Hive, passei para o tratamento do PIX, então criei um Endpoint para receber as notificações recebidas do PIX e logar na tela.

Usando o sandbox da API do Banco criei um novo evento pix recebido, que acionou o endpoint PixBee e pôde recebêr sem problemas.

image.png

Recebendo Hive

Percebi que muitos dos valores recebidos daquela exchange eram muito altos (pelo menos para mim), então tive a ideia de incluir alguns limites de exchange até que eu tivesse fundos suficientes para viabilizar aquela transação.

Quero torná-lo flexível, para que um usuário possa comprar ou vender todo o valor disponível, em vez de limitar, mas outro recurso está por vir. Só os condados têm limites, certo?

Quem tem Limite é Município?

Então, estabeleci dois limites, o mínimo e o máximo. E uma taxa pela utilização do serviço e não respeita os valores mínimo e máximo de depósitos. Inicialmente definido como 7%, mas talvez seja muito alto, não tenho certeza, não estou pensando em taxas no momento. PixBee pode alterá-lo facilmente, basta configurar um novo valor para aquela var e podemos aproveitar isso para criar períodos de promoções, aumentar ou diminuir impostos com facilidade.

Até agora temos estes valores:

LimitsValue
MinimumR$ 50
MaximumR$ 200
Service Fee7%
Service Fee2%
Fixed FeeR$ 2

E com isso, agora o PixBee pode lidar com erros Fora do Limite. Legal!

Out of Limits, value too high

Enviando HIVE

Um evento crítico a ser resolvido agora, para poder enviar o HIVE, o PixBee precisará de uma chave ativa válida e qualquer erro de código pode permitir que o PixBee fique sem fundos. Neste momento tentei usar o HIVE Testnet, mas descobri que ainda não está disponível.

Preciso criar meu próprio Hive Testnet para poder testar sem enviar meu PixBee HIVE.

Sem Testnet disponível, decidi agir dessa forma. PixBee criará o objeto de transferência, mas não o transmitirá para a rede principal do Hive. basta registrar na tela os dados da transferência.

image.png

Tentei usar alguns códigos de cores para identificar facilmente que tipo de transação estava sendo recebida, Verde para Hive Recebido, Vermelho para Erros e Azul para transações.

Processo de reembolso

Parece que o processo está quase pronto, podemos Receber PIX e prontos para enviar HIVE, podemos Receber Hive e talvez precisemos de Reembolso, vamos tentar o processo.

Receba Hive ou PIX e trate com possibilidade de tratar erros no meio.

Agora a chave é transmitir ao Hive a informação de que ainda não irei testar. O código está pronto, mas o sinalizador para registrar apenas a transferência do objeto não vou transmiti-lo. E parece que está pronto para funcionar.

image.png

image.png

image.png

Tipos de Chaves Pix

Para quem não está acostumado com a chave Pix (os gringos talvez), ela pode ter 4 tipos:

CPF999.999.999-99
Celular(99)99999-9999
Email[email protected]
CNPJ99.999.999/9999-99
EVPChave Aleatóriaxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

A princípio, vou aceitar apenas a chave Aleatória como parâmetro para tratar as transferências PIX, mas os tipos mais comuns utilizados são Celular ou CPF, e para CNPJ. Não tenho certeza se as pessoas vão querer ter alguns dados pessoais como CPF registrados no blockchain, mas... vamos deixar isso como recurso futuro.

Agora precisamos pegar a descrição do HIVE MEMO e obter a chave PIX.

Para tornar isso possível, crio outro sinalizador de configuração de script para testar a transferência e, nesse caso, substituo o MEMO por uma EVP KEY válida.

Dessa forma, eu poderia testar formatos de chave EVP errados e formatos de EVP corretos com modificação mínima em meu código, apenas configurando um sinalizador.

Validating EVP Key

Após armazenar todas as informações recebidas como usuário, chave, valor do hive e valor convertido em reais, caso ocorra algum erro nas próximas transações, o PixBee consegue reembolsar ao usuário sem nenhum esforço.

E funcionou perfeitamente. Cada vez que a PixBee recebia uma CHAVE EVP errada (todas as transações até agora), a PixBee poderia reembolsar o usuário imediatamente.

Transferências sem Memo

Como eu tinha como alvo duas contas para receber dados de teste, uma delas recebe todos os HIVE sem chave MEMO. A princípio pensei que poderia ser um erro do usuário ao transferi-lo para o PixBee e o bot PixBee identificará como erro e reembolsará o usuário imediatamente.

Mas depois de algumas transações, algo me veio à mente. Como os usuários podem dar DICA ao serviço ou se o bot PixBee precisa receber algum valor que não seja para transferência PIX?

A solução foi implementar um ‘TIP Honey Pot’, e caso o usuário realmente tenha cometido algum erro, será necessário Abrir um Ticket para recuperar esse valor manualmente.

Acho que a PixBee precisa de um assistente para lidar com esses problemas de ingressos. Talvez um canal de suporte do Whatsapp conectado à IA para lidar com esse tipo de tickets.

Yeah!

Sem Saldo?

Como o PixBee ainda não está lidando com o saldo baixo das contas, acho que é o próximo passo para a configuração. Precisarei obter o saldo da conta PixBee Hive e o saldo da minha conta PIX para que o PixBee possa saber se concluiu a transação antes mesmo de iniciá-la.

É um bom momento para reflexão, pausa e enfeitar os códigos.

Você está vendo capturas de tela coloridas, mas no começo eram códigos e mais códigos que eram difíceis de ler todos esses códigos, mesmo para mim que os estava criando.

Demorou algum tempo para melhorar e refatorar alguns códigos e embelezar os logs. Além disso, quero simplificar, como apenas uma linha, para não rolar muita tela.

Quanto mais eu codifico, mais a lista de TODO aumenta, haha

image.png




Sort:  

Estou desinstalando a Binance para utilizar isso agora mesmo.

Ai sim! Quero lançar logo o beta test e ja preparei umas taxas promocionais.

Alpha test funcionou bem!

To preparando um frontend pra exibir informações de forma legal para usuários.

Logo mais informações no Discord hivebr.

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.

Parabéns irmão, queria saber fazer disso daí, que sabe na próxima vida!
!PGM
!WINE

Valeu! nao seja por isoo... se quiser eu ensino!

Testado e aprovado! Ta incrível meu amigo, o pixbee vai conquistar a todos!

!PGM !LOLZ !PIMP


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

Why are ducks good at playing limbo?
Because they can get down.

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 pelo suporte Shift e pela ajuda no teste!

Fico muito feliz em saber que vc curtiu e aprovou!

abs

Tamo junto parceiro! Seu projeto vai se tornar uma grande referência para a hive!

da hora mano ta ficando loko

valeu! obrigado pela ajuda nos testes


Your post was manually curated by @CrazyPhantomBR.
banner_hiver_br_01.png

Delegate your HP to the hive-br.voter account and earn Hive daily!

🔹 Follow our Curation Trail and don't miss voting! 🔹

Congratulations @vaipraonde! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

You distributed more than 31000 upvotes.
Your next target is to reach 32000 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Check out our last posts:

Unveiling the BuzzParty Meetup 2024 Badge