PixBee Bot - Not just another HIVE Bot - part3

Wrote in Portuguese and translated to English using GT.


pixbee-ascii-art.png

Hi HiveDevs friends! how are you doing this weekend?

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

In this post I will show the third part of Pixbee's development, which consisted of testing, bug fixes and more testing.

In addition to an extensive code review to normalize all functions.


Send and receive

After implementing the transfer identification routines on the Hive and PIX blockchain, it was time to test whether everything would work.

Since I didn't create a test network in Hive, I needed to develop an alternative plan:

To get around the minimum deposit requirement, I created a test setup where, at the exact moment of signing and sending the transaction, I changed the value to 0.001 HIVE and sent it.

This way, it ensured that the transaction was executed successfully without the need to send the minimum deposit required by Pixbee.

image.png

And the plan worked! I was able to send and receive transactions on Hive.

However, I wasn't satisfied with having the data exposed in the Memo field, which led me to add a new item to my to-do list:

  • Implement Memo encryption on Pixbee.

Test Scenarios

With the option to test the transaction with 0.001 HIVE, I developed a new functionality that only displays the information on the screen, without actually sending it to the Blockchain.

This made it possible to test different scenarios and verify whether the treatments for these scenarios were being executed successfully.

image.png


image.png

Some of the test scenarios include:

  • Seamless transfer on the blockchain.
  • Perfect transfer via PIX.
  • Invalid Hive user.
  • Nonexistent Hive user.
  • Incorrect PIX keys.
  • Without PIX key.
  • No Memo field.
  • With Memo containing token and message.
  • Error returned when sending transactions on the Hive blockchain.
  • Error returned when sending transactions on PIX.
  • Insufficient balance in Hive account.
  • Insufficient balance in the PIX account.
  • Transfer below minimum deposit.
  • If these conditions result in an error, a Refund Ticket is generated and then returned to the user.

After identifying some bugs and reevaluating validation priorities, I fixed all the errors I caught along the way.

Stress Test

image.png

For the stress test, I implemented routines that generated transactions with random values and monitored Pixbee's performance.

The tests were completed successfully, and so I decided to carry out a complete code refactoring, breaking everything down and needing to test each part again.

It took approximately 17 hours of testing without encountering any problems.

Improvements

Before starting the refactoring, I chose to take the opportunity to rethink the system and include the new features I had planned.

Initially, I was thinking about postponing these changes to a future release, but I decided it was the right time to implement.

This approach saved me the trouble of having to test everything again later.

Although it took a little longer to plan everything, once I was done, I was able to implement some significant improvements before starting the refactoring process. Some of the improvements implemented were:

Circuit Break

Implementation of a Circuit Breaker, which stops trading if the TOKEN value is below the defined average value. This solution arose from an extensive discussion on how to allow transactions with HIVE without exposing Pixbee to losses in cases of "buy high sell low".

I didn't want to only allow HBD, and this opened up new possibilities, now I could make a Pix with Hive's L2 tokens easily, including new tokens in the list of accepted tokens.

image.png

Memos Encryption

image.png

Yes, the community won and we will implement encrypted Memos for Hive transactions.

Now your keys and information are secure with Hive encryption!

image.png

Custom Log System

I implemented a custom LOG system, creating a buffer to store log messages and writing to disk only when the buffer is full. This way, I avoid accessing the disk multiple times during the process.

This system also allows me to create separate logs for different cases, such as Refund, Errors, Tickets and Success.

This will be extremely helpful in resolving issues when they occur.

And yes, I didn't forget to do the Log Flush when intercepting Control+C.

Custom Database System

I decided not to use a robust solution to store some bot statistics that I didn't want to lose upon restart.

Some of these statistics include the average value of tokens when receiving deposits, average value of deposits to adjust limits as necessary, largest and smallest amounts deposited, tips received, fees collected, among other information.

To do this, I developed a system to access and save this data in a JSON file, and I believe it worked better than expected. While I recognize it's not an ideal solution, at least now I don't lose data when I restart the bot.

More Tests

image.png

With the new implementations completed and the code revised, it's time to perform more tests.

I added breakpoints practically at every point in the code and tested case by case, analyzing the behavior and correcting some bugs, in addition to improving some conditions.

After reviewing it several times and ensuring that everything was in order, it was time to perform another stress test. For this new test, I created 36 test scenarios, sending HBD, Hive, other tokens and even sending nothing, with errors or missing information.

More Stress Tests

During 1 hour of testing, several transactions were created, resulting in an average of 56.25 transactions per minute, with the following numbers:

TypeQuantity of Transactions
PIX received1537
HBD received1169
HIVE received669

Many of these transactions occurred simultaneously, as at times the timers coincided.

All treatments were carried out successfully, and I was satisfied with the results, especially considering that it was the first time I worked intensively with async and wait in Node.js, as well as other more advanced features.

Unexpected Bug

It was at this point that I came across two major unexpected bugs.

As the bot was running in production in parallel to my testing environment, I decided to do a SWAP using @keychain, which resulted in a bot battle.

image.png

Nobody wanted to keep 66 HBD, and Pixbee returned transactions because it didn't have a Pix key, resulting in 18 transactions on each side.

I was pleased with the result and it increased my confidence in the Hive Key Chain service, especially after @shiftrox commented to me that a certain large exchange did not return incorrectly sent HBDs for their accounts.

This also made me realize that since I had already set my Memo key in Hive-js, there was no need to hardcode the Memo before sending.

Double encoding of Memo was occurring, and I went back to fix this issue.

image.png

Conclusion

Now I'm more confident about releasing a Release Candidate version and to further test this confidence, I left the tests running overnight and then decided to keep them running during the day as well.

There were more than 20 hours of testing, with 36 different scenarios with random values and with the Circuit Break activated randomly, depending on a list of values specified between $0.3 - $0.5 in HIVE value.

I carried out an audit of the logs and everything indicates that it is working as expected.

image.png







Versão Brasileira

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

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

Neste post vou mostrar a terceira parte do desenvolvimento da Pixbee, que foram de testes, correcoes de bugs e mais testes.

Além de uma extensa revisão de códigos para normalizar todas as funções.


Enviar e Receber

Após implementar as rotinas de identificação de transferências na blockchain da Hive e de PIX, chegou a hora de testar se tudo iria funcionar.

Como não criei uma rede de testes na Hive, precisei desenvolver um plano alternativo:

Para contornar o requisito de depósito mínimo, criei uma configuração de teste na qual, no momento exato de assinar e enviar a transação, eu modificava o valor para 0.001 HIVE e o enviava.

Dessa forma, garantia que a transação fosse executada com sucesso sem a necessidade de enviar o depósito mínimo requerido pela Pixbee.

image.png

E o plano deu certo! Consegui enviar e receber transações na Hive.

No entanto, não fiquei satisfeito em ter os dados expostos no campo Memo, o que me levou a adicionar um novo item à minha lista de tarefas:

  • Implementar a criptografia do Memo na Pixbee.

Cenários de Testes

Com a opção de testar a transação com 0.001 HIVE, desenvolvi uma nova funcionalidade que apenas exibe as informações na tela, sem efetivamente enviar para a Blockchain.

Isso possibilitou testar diversos cenários e verificar se os tratamentos desses cenários estavam sendo executados com sucesso.

image.png


image.png

Alguns dos cenários de teste incluem:

  • Envio perfeito na blockchain.
  • Envio perfeito no PIX.
  • Usuário da Hive inválido.
  • Usuário da Hive inexistente.
  • Chaves PIX incorretas.
  • Sem chave PIX.
  • Sem campo Memo.
  • Com Memo contendo token e mensagem.
  • Retorno de erro ao enviar transações na blockchain da Hive.
  • Retorno de erro ao enviar transações no PIX.
  • Saldo insuficiente na conta da Hive.
  • Saldo insuficiente na conta do PIX.
  • Transferência abaixo do depósito mínimo.
  • Caso essas condições resultem em erro, é gerado um Ticket de Reembolso e então devolvido ao usuário.

Após identificar alguns bugs e reavaliar as prioridades de validações, corrigi todos os erros que peguei pelo caminho.

Stress Test

image.png

Para o teste de estresse, implementei rotinas que geravam transações com valores aleatórios e monitorava o desempenho da Pixbee.

Os testes foram concluídos com sucesso, e então decidi realizar uma refatoração de código completa, desmembrando tudo e necessitando testar novamente cada parte.

Foram aproximadamente 17 horas de teste sem encontrar nenhum problema.

Melhorias

Antes de iniciar a refatoração, optei por aproveitar a oportunidade para repensar o sistema e incluir as novas funcionalidades que eu tinha planejado.

Inicialmente, estava pensando em adiar essas mudanças para uma versão futura, mas decidi que era o momento certo para implementar.

Essa abordagem me poupou o trabalho de ter que testar tudo novamente posteriormente.

Embora tenha levado um pouco mais de tempo para planejar tudo, após concluir, consegui implementar algumas melhorias significativas antes de iniciar o processo de refatoração. Algumas das melhorias implementadas foram:

Circuit Break

Implementação de um Circuit Breaker, que interrompe a negociação caso o valor do TOKEN esteja abaixo do valor médio definido. Essa solução surgiu de uma extensa discussão sobre como permitir transações com HIVE sem expor a Pixbee a prejuízos em casos de "buy high sell low".

Não queria permitir somente HBD, e isso abriu novas possibilidades, agora poderia fazer um Pix com tokens L2 da Hive facilmente, incluindo novos tokens na lista de tokens aceitos.

image.png

Criptografia nos Memos

image.png

Sim, a comunidade venceu e vamos implementar Memos criptografado para as transacoes da Hive.

Agora as chaves e informações ficaram seguras com a criptografia Hive!

image.png

Custom Log System

Implementei um sistema de LOG personalizado, criando um buffer para armazenar as mensagens de log e escrevendo no disco somente quando o buffer estiver cheio. Dessa forma, evito acessar o disco várias vezes durante o processo.

Esse sistema também me permite criar logs separados para diferentes casos, como Refund, Errors, Tickets e Success.

Isso será extremamente útil na resolução de problemas quando eles ocorrerem.

E sim, não esqueci de fazer o Log Flush ao interceptar o Control+C.

Custom Database System

Decidi não utilizar uma solução robusta para armazenar algumas estatísticas do bot que não queria perder ao reiniciar.

Algumas dessas estatísticas incluem o valor médio dos tokens ao receber depósitos, valor médio dos depósitos para ajustar limites conforme necessário, os maiores e menores valores depositados, tips recebidas, taxas recolhidas, entre outras informações.

Para isso, desenvolvi um sistema para acessar e salvar esses dados em um arquivo JSON, e acredito que funcionou melhor do que o esperado. Embora reconheça que não é a solução ideal, pelo menos agora não perco os dados ao reiniciar o bot.

Mais Testes

image.png

Com as novas implementações concluídas e o código revisado, chegou a hora de realizar mais testes.

Adicionei breakpoints praticamente em todos os pontos do código e fui testando caso a caso, analisando o comportamento e corrigindo alguns bugs, além de melhorar algumas condições.

Após revisar várias vezes e garantir que tudo estava em ordem, chegou o momento de realizar mais um teste de estresse. Para este novo teste, criei 36 cenários de teste, enviando HBD, Hive, outros tokens e até mesmo não enviando nada, com erros ou informações faltando.

Mais Testes de Estresse

Durante 1 hora de teste, foram criadas várias transações, resultando em uma média de 56.25 transações por minuto, com os seguintes números:

Tipo de TransferênciaQuantidade de Transações
PIX recebidos1537
HBD recebidos1169
HIVE recebidos669

Muitas dessas transações ocorreram simultaneamente, pois em alguns momentos os timers coincidiam.

Todos os tratamentos foram realizados com sucesso, e fiquei satisfeito com os resultados, especialmente considerando que era a primeira vez que trabalhei intensamente com async e wait em Node.js, além de outras funcionalidades mais avançadas.

Bug Inexperado

Foi nesse momento que me deparei com dois grandes bugs inesperados.

Como estava com o bot rodando em produção em paralelo ao meu ambiente de testes, decidi fazer um SWAP usando o @keychain, o que resultou em uma batalha de bots.

image.png

Ninguém queria ficar com 66 HBD, e o Pixbee devolvia as transações por não ter chave Pix, resultando em 18 transações de cada lado.

Fiquei satisfeito com o resultado e isso aumentou minha confiança no serviço do Hive Key Chain, especialmente depois que @shiftrox comentou comigo que uma certa grande corretora não devolveu HBDs enviados errados para suas contas.

Isso também me fez perceber que, como eu já havia definido minha chave Memo no Hive-js, não era necessário codificar o Memo antes de enviar.

Estava ocorrendo uma codificação dupla do Memo, e voltei para corrigir esse problema.

image.png

Conclusão

Agora estou mais confiante para lançar uma versão Release Candidate e para testar ainda mais essa confiança, deixei os testes rodando durante a noite e depois decidi mantê-los também durante o dia.

Foram mais de 20 horas de testes, com 36 cenários diferentes com valores aleatórios e com o Circuit Break ativado aleatoriamente, dependendo de uma lista de valores especificados entre $0.3 - $0.5 no valor do HIVE.

Realizei uma auditoria nos logs e tudo indica que está funcionando conforme o esperado.

image.png




H2
H3
H4
3 columns
2 columns
1 column
10 Comments
Ecency