client.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. const util = require("util");
  2. const addr1 = "foo";
  3. const addr2 = "bar";
  4. const fee = "fee";
  5. const percentage = 0.005;
  6. function dbg(obj) {
  7. console.log(util.inspect(obj, false, null, true /* enable colors */))
  8. }
  9. async function get_balance(account) {
  10. const response = await fetch(`http://127.0.0.1:8080/balance/${account}`);
  11. return response.json();
  12. }
  13. async function deposit(account, amount, asset) {
  14. const response = (await fetch("http://127.0.0.1:8080/deposit", {
  15. method: "POST",
  16. headers: {
  17. "Content-Type": "application/json",
  18. },
  19. body: JSON.stringify({
  20. memo: "deposit",
  21. account,
  22. amount: amount.toString(),
  23. asset,
  24. status: 'pending',
  25. })
  26. }));
  27. return response.json();
  28. }
  29. async function trade(amount, asset, from, amount_to, asset_to, to) {
  30. const response = (await fetch("http://127.0.0.1:8080/tx", {
  31. method: "POST",
  32. headers: {
  33. "Content-Type": "application/json",
  34. },
  35. body: JSON.stringify({
  36. memo: "trade",
  37. debit: [
  38. {
  39. account: from,
  40. amount: amount.toString(),
  41. asset
  42. },
  43. {
  44. account: to,
  45. amount: amount_to.toString(),
  46. asset: asset_to,
  47. }
  48. ],
  49. credit: [
  50. {
  51. account: to,
  52. amount: (amount * (1 - percentage)).toString(),
  53. asset
  54. },
  55. {
  56. account: from,
  57. amount: amount_to.toString(),
  58. asset: asset_to
  59. },
  60. {
  61. account: fee,
  62. amount: (amount * percentage).toString(),
  63. asset
  64. }
  65. ],
  66. status: 'pending',
  67. asset,
  68. })
  69. }));
  70. return response.json();
  71. }
  72. async function change_status(id, s_status) {
  73. const response = (await fetch(`http://127.0.0.1:8080/${id}`, {
  74. method: "POST",
  75. headers: {
  76. "Content-Type": "application/json",
  77. },
  78. body: JSON.stringify({
  79. status: s_status,
  80. memo: `change status to ${s_status}`,
  81. })
  82. }));
  83. return response.json();
  84. }
  85. async function test() {
  86. let d = (await deposit(addr1, 1.5, "BTC/8"));
  87. dbg(d);
  88. dbg(await change_status(d._id, 'settled'));
  89. d = (await deposit(addr2, 1000000, "USD/4"));
  90. dbg(await change_status(d._id, 'settled'));
  91. const t = await trade(1, "BTC/8", addr1, 26751.11, "USD/4", addr2);
  92. dbg(t);
  93. dbg(await change_status(t._id, 'processing',));
  94. dbg(await change_status(t._id, 'settled'));
  95. dbg(await get_balance(addr1));
  96. dbg(await get_balance(addr2));
  97. dbg(await get_balance(fee));
  98. }
  99. test()