aboutsummaryrefslogtreecommitdiffstats
path: root/routes/swaps.js
blob: ee04728699925d4cbcd15a9c83ce360672a98606 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888 } /* Comment */
.highlight .err { color: #A61717; background-color: #E3D2D2 } /* Error */
.highlight .k { color: #080; font-weight: bold } /* Keyword */
.highlight .ch { color: #888 } /* Comment.Hashbang */
.highlight .cm { color: #888 } /* Comment.Multiline */
.highlight .cp { color: #C00; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888 } /* Comment.Single */
.highlight .cs { color: #C00; font-weight: bold; background-color: #FFF0F0 } /* Comment.Special */
.highlight .gd { color: #000; background-color: #FDD } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #A00 } /* Generic.Error */
.highlight .gh { color: #333 } /* Generic.Heading */
.highlight .gi { color: #000; background-color: #DFD } /* Generic.Inserted */
.highlight .go { color: #888 } /* Generic.Output */
.highlight .gp { color: #555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666 } /* Generic.Subheading */
.highlight .gt { color: #A00 } /* Generic.Traceback */
.highlight .kc { color: #080; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #080; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #080; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #080 } /* Keyword.Pseudo */
.highlight .kr { color: #080; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #00D; font-weight: bold } /* Literal.Number */
.highlight .s { color: #D20; background-color: #FFF0F0 } /* Literal.String */
.highlight .na { color: #369 } /* Name.Attribute */
.highlight .nb { color: #038 } /* Name.Builtin */
.highlight .nc { color: #B06; font-weight: bold } /* Name.Class */
.highlight .no { color: #036; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555 } /* Name.Decorator */
.highlight .ne { color: #B06; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #06B; font-weight: bold } /* Name.Function */
.highlight .nl { color: #369; font-style: italic } /* Name.Label */
.highlight .nn { color: #B06; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #369; font-weight: bold } /* Name.Property */
.highlight .nt { color: #B06; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #369 } /* Name.Variable */
.highlight .ow { color: #080 } /* Operator.Word */
.highlight .w { color: #BBB } /* Text.Whitespace */
.highlight .mb { color: #00D; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #00D; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #00D; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #00D; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #00D; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #D20; background-color: #FFF0F0 } /* Literal.String.Affix */
.highlight .sb { color: #D20; background-color: #FFF0F0 } /* Literal.String.Backtick */
.highlight .sc { color: #D20; background-color: #FFF0F0 } /* Literal.String.Char */
.highlight .dl { color: #D20; background-color: #FFF0F0 } /* Literal.String.Delimiter */
.highlight .sd { color: #D20; background-color: #FFF0F0 } /* Literal.String.Doc */
.highlight .s2 { color: #D20; background-color: #FFF0F0 } /* Literal.String.Double */
.highlight .se { color: #04D; background-color: #FFF0F0 } /* Literal.String.Escape */
.highlight .sh { color: #D20; background-color: #FFF0F0 } /* Literal.String.Heredoc */
.highlight .si { color: #33B; background-color: #FFF0F0 } /* Literal.String.Interpol */
.highlight .sx { color: #2B2; background-color: #F0FFF0 } /* Literal.String.Other */
.highlight .sr { color: #080; background-color: #FFF0FF } /* Literal.String.Regex */
.highlight .s1 { color: #D20; background-color: #FFF0F0 } /* Literal.String.Single */
.highlight .ss { color: #A60; background-color: #FFF0F0 } /* Literal.String.Symbol */
.highlight .bp { color: #038 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #06B; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #369 } /* Name.Variable.Class */
.highlight .vg { color: #D70 } /* Name.Variable.Global */
.highlight .vi { color: #33B } /* Name.Variable.Instance */
.highlight .vm { color: #369 } /* Name.Variable.Magic */
.highlight .il { color: #00D; font-weight: bold } /* Literal.Number.Integer.Long */
module.exports = {
  plugins: {
    "@tailwindcss/postcss": {},
  },
};
='n211' href='#n211'>211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
const axios = require("axios");
const crypto = require("crypto");
const fs = require("fs");
const getAccount = require("../lib/account");
const { Op, col } = require("sequelize");
const uuidv4 = require("uuid/v4");

const debug = require('debug')('debug')

const shallow = a => {
  let b = {};
  for (x in a) {
    if (a[x] instanceof Date || typeof a[x] !== "object") b[x] = a[x];
  }
  return b;
};

const assets = {
  b2e15d0d7a0c94e4e2ce0fe6e8691b9e451377f6e46e8045a86f7c4b5d4f0f23: "bitcoin",
  "4eebe36eb0819e6daa5dd3c97733251ff4eb728c810d949365d6dacaad5ef6e8": "tether"
};

const timeout = 20000;

const swap = async (user, { a1, a2, v1, v2 }) => {
  if (!parseInt(v1) || v1 < 0 || !parseInt(v2) || v2 < 0)
    throw new Error("Invalid amount");
  let rate = v2 / v1;

  const b = await lq.getBalance();

  Object.keys(b).map(asset => {
    assets[asset] = asset;
  });

  assets[config.liquid.btcasset] = "bitcoin";
  assets["ce091c998b83c78bb71a632313ba3760f1763d9cfcffae02258ffa9865a37bd2"] =
    "tether";
  assets["a0c358a0f6947864af3a06f3f6a2aeb304df7fd95c922f2f22d7412399ce7691"] =
    "adamcoin";

  if (!assets[a1]) throw new Error("Asset not found on server");
  if (v1 > Math.round(b[assets[a1]] * SATS))
    throw new Error(`Insufficient server funds, ${v1} ${b[assets[a1]]}`);

  await db.transaction(async transaction => {
    let a1acc = await getAccount(a1, user, transaction);
    let a2acc = await getAccount(a2, user, transaction);

    if (v1 > a1acc.balance)
      throw new Error(`Insufficient funds, ${v1} ${a1acc.balance}`);

    l.info(
      `placing order ${v1} ${a1.substr(0, 6)} for ${v2} ${a2.substr(0, 6)}`,
      user.username
    );

    await a1acc.decrement({ balance: v1 }, { transaction });
    await a1acc.reload({ transaction });

    let payment = await db.Payment.create(
      {
        hash: "Trade Funding",
        amount: -v1,
        account_id: a1acc.id,
        user_id: user.id,
        currency: user.currency,
        rate: app.get("rates")[user.currency],
        confirmed: true,
        received: false,
        network: "COINOS"
      },
      { transaction }
    );

    emit(user.username, "payment", payment.get({ plain: true }));
    emit(user.username, "account", a1acc.get({ plain: true }));

    const orders = await db.Order.findAll(
      {
        where: {
          "$acc1.asset$": a2,
          "$acc2.asset$": a1,
          rate: { [Op.lte]: v1 / v2 },
          accepted: false
        },
        order: [
          ["rate", "ASC"],
          ["id", "ASC"]
        ],
        include: [
          {
            model: db.User,
            as: "user"
          },
          {
            model: db.Account,
            as: "acc1"
          },
          {
            model: db.Account,
            as: "acc2"
          }
        ]
      },
      { transaction }
    );

    for (let i = 0; i < orders.length; i++) {
      if (!v1) break;
      let order = orders[i];
      if (order.v2 > v1) {
        let rate = order.rate;
        await order.decrement(
          {
            v2: v1
          },
          { transaction }
        );
        await order.save({ transaction });
        await order.reload({ transaction });
        order.v1 = Math.round(order.v2 / rate);
        await order.save({ transaction });

        await order.acc1.increment({ balance: v2 }, { transaction });
        await order.acc1.reload({ transaction });

        emit(order.user.username, "account", order.acc1.get({ plain: true }));

        payment = await db.Payment.create(
          {
            hash: "Trade Fill",
            amount: v1,
            account_id: a1acc.id,
            user_id: user.id,
            currency: user.currency,
            rate: app.get("rates")[user.currency],
            confirmed: true,
            received: true,
            network: "COINOS"
          },
          { transaction }
        );

        emit(user.username, "payment", payment.get({ plain: true }));
        emit(user.username, "account", a1acc.get({ plain: true }));

        if (order.fee) {
          const btc = await getAccount(
            config.liquid.btcasset,
            order.user,
            transaction
          );

          payment = await db.Payment.create(
            {
              hash: "Swap Fee Refund",
              amount: order.fee,
              account_id: btc.id,
              user_id: order.user_id,
              currency: order.user.currency,
              rate: app.get("rates")[order.user.currency],
              confirmed: true,
              received: true,
              network: "COINOS"
            },
            { transaction }
          );

          await btc.increment({ balance: order.fee }, { transaction });
          await btc.reload({ transaction });

          emit(order.user.username, "account", btc.get({ plain: true }));
        }

        emit(order.user.username, "payment", payment.get({ plain: true }));

        order = order.get({ plain: true });
        order.a1 = order.acc1.asset;
        order.a2 = order.acc2.asset;
        order.rate = order.v2 / order.v1;

        broadcast("order", shallow(order));
        v1 = 0;
      } else {
        v1 -= order.v2;
        v2 = Math.round(v1 * rate);

        order.accepted = true;
        order.completedAt = new Date();

        await order.save({ transaction });

        let payment = await db.Payment.create(
          {
            hash: "Trade Fill",
            amount: order.v1,
            account_id: a2acc.id,
            user_id: user.id,
            currency: user.currency,
            rate: app.get("rates")[user.currency],
            confirmed: true,
            received: true,
            network: "COINOS"
          },
          { transaction }
        );

        await a2acc.increment({ balance: order.v1 }, { transaction });
        await a2acc.reload({ transaction });

        emit(user.username, "payment", payment.get({ plain: true }));
        emit(user.username, "account", a2acc.get({ plain: true }));

        payment = await db.Payment.create(
          {
            hash: "Trade Fill",
            amount: order.v2,
            account_id: order.a2_id,
            user_id: order.user_id,
            currency: order.user.currency,
            rate: app.get("rates")[order.user.currency],
            confirmed: true,
            received: true,
            network: "COINOS"
          },
          { transaction }
        );

        emit(order.user.username, "payment", payment.get({ plain: true }));
        await order.acc2.increment({ balance: order.v2 }, { transaction });
        await order.acc2.reload({ transaction });

        order = order.get({ plain: true });
        order.a1 = order.acc1.asset;
        order.a2 = order.acc2.asset;
        order.rate = order.v2 / order.v1;

        broadcast("order", shallow(order));
      }
    }

    let order;
    if (v1) {
      order = await db.Order.create(
        {
          v1,
          v2,
          user_id: user.id,
          a1_id: a1acc.id,
          a2_id: a2acc.id
        },
        { transaction }
      );

      order = order.get({ plain: true });
      order.rate = v2 / v1;
      order.a1 = a1;
      order.a2 = a2;

      broadcast("order", order);
    }
  });
};

const cancel = async (user, id) => {
  await db.transaction(async transaction => {
    let order = await db.Order.findOne(
      {
        where: {
          id,
          user_id: user.id
        },
        include: {
          model: db.Account,
          as: "acc1"
        }
      },

      { transaction }
    );

    let { acc1: account, v1, v2 } = order;
    await account.increment({ balance: v1 }, { transaction });
    await account.reload({ transaction });

    let rate = v2 / v1;
    let payment = await db.Payment.create(
      {
        hash: "Trade Cancelled",
        amount: v1,
        account_id: account.id,
        user_id: user.id,
        currency: user.currency,
        rate: app.get("rates")[user.currency],
        confirmed: true,
        received: true,
        network: "COINOS"
      },
      { transaction }
    );

    emit(user.username, "account", account.get({ plain: true }));
    emit(user.username, "payment", payment.get({ plain: true }));

    if (order.fee) {
      const btc = await getAccount(config.liquid.btcasset, user, transaction);

      payment = await db.Payment.create(
        {
          hash: "Swap Fee Refund",
          amount: order.fee,
          account_id: btc.id,
          user_id: user.id,
          currency: user.currency,
          rate: app.get("rates")[user.currency],
          confirmed: true,
          received: true,
          network: "COINOS"
        },
        { transaction }
      );

      await btc.increment({ balance: order.fee }, { transaction });
      await btc.reload({ transaction });

      emit(user.username, "account", btc.get({ plain: true }));
      emit(user.username, "payment", payment.get({ plain: true }));
    }

    broadcast("removeOrder", id);
    await order.destroy({ transaction });
  });
};

app.delete(
  "/order/:id",
  auth,
  ah(async (req, res) => {
    const { id } = req.params;
    const { user } = req;

    await cancel(user, id);
    res.end();
  })
);

app.post(
  "/orders",
  auth,
  ah(async (req, res) => {
    return res.status(500).send("Trading temporarily disabled");
    const { user } = req;
    try {
      await swap(user, req.body);
      res.end();
    } catch (e) {
      l.error(req.user.username, e.message);
      res.status(500).send(e.message);
    }
  })
);

app.get(
  "/orders",
  optionalAuth,
  ah(async (req, res) => {
    try {
      let orders = await db.Order.findAll({
        attributes: {
          include: [
            [col("acc1.asset"), "a1"],
            [col("acc2.asset"), "a2"]
          ]
        },
        include: [
          {
            model: db.Account,
            as: "acc1",
            attributes: []
          },
          {
            model: db.Account,
            as: "acc2",
            attributes: []
          }
        ]
      });

      res.send(
        orders.map(order => {
          if (order.user_id !== req.user.id) order.user_id = null;
          return order;
        })
      );
    } catch (e) {
      res.status(500).send(e.message);
    }
  })
);

if (config.maker) {
  debug('setup maker account...')
  config.maker.map(({ amount, c1, c2, currency, askMultiplier, bidMultiplier }) => {
    setInterval(async () => {
      if (!app.get("rates")) return;

      const user = await db.User.findOne({
        where: {
          username: "maker"
        }
      });

      if (!user) {
        debug('maker user not defined in database')
      } else {
        debug('maker: ' + JSON.stringify(user))
        await db.transaction(async transaction => {
          let order = await db.Order.findOne(
            {
              where: {
                user_id: user.id,
                "$acc1.asset$": c1,
                "$acc2.asset$": c2,
                accepted: false
              },
              include: [
                {
                  model: db.Account,
                  as: "acc1"
                },
                {
                  model: db.Account,
                  as: "acc2"
                }
              ]
            },
            { transaction }
          );

          let params = {
            a1: c1,
            a2: c2,
            v1: amount * SATS,
            v2: Math.round(
              amount *
                SATS *
                (((app.get("ask") * app.get("rates")[currency]) /
                  app.get("rates")["USD"]) *
                  askMultiplier)
            )
          };

          if (order) {
            let bestBid = await db.Order.findOne(
              {
                where: {
                  "$acc1.asset$": c2,
                  "$acc2.asset$": c1,
                  accepted: false,
                  id: {
                    [Op.ne]: order.id
                  }
                },
                include: [
                  {
                    model: db.Account,
                    as: "acc1"
                  },
                  {
                    model: db.Account,
                    as: "acc2"
                  }
                ],
                order: [["rate", "DESC"]],
                limit: 1
              },
              { transaction }
            );
            if (
              !bestBid ||
              (params.v2 / params.v1 > bestBid.rate &&
                order.acc2.balance >= params.v2)
            ) {
              order.v1 = params.v1;
              order.v2 = params.v2;
              await order.save();
              order = order.get({ plain: true });
              order.a1 = params.a1;
              order.a2 = params.a2;
              order.rate = order.v2 / order.v1;

              broadcast("order", shallow(order));
            }
          } else {
            try {
              await swap(user, params);
            } catch (e) {
              l.warn("Failed to make ask", e.message);
            }
          }

          order = await db.Order.findOne(
            {
              where: {
                user_id: user.id,
                "$acc1.asset$": c2,
                "$acc2.asset$": c1,
                accepted: false
              },
              include: [
                {
                  model: db.Account,
                  as: "acc1"
                },
                {
                  model: db.Account,
                  as: "acc2"
                }
              ]
            },
            { transaction }
          );

          params = {
            a1: c2,
            a2: c1,
            v1: Math.round(
              amount *
                SATS *
                ((app.get("bid") * app.get("rates")[currency]) /
                  app.get("rates")["USD"]) *
                bidMultiplier
            ),
            v2: amount * SATS
          };

          if (order) {
            let bestAsk = await db.Order.findOne(
              {
                where: {
                  "$acc1.asset$": c1,
                  "$acc2.asset$": c2,
                  accepted: false,
                  id: {
                    [Op.ne]: order.id
                  }
                },
                include: [
                  {
                    model: db.Account,
                    as: "acc1"
                  },
                  {
                    model: db.Account,
                    as: "acc2"
                  }
                ],
                order: [["rate", "ASC"]],
                limit: 1
              },
              { transaction }
            );

            if (bestAsk)
              if (
                !bestAsk ||
                (params.v1 / params.v2 < bestAsk.rate &&
                  order.acc1.balance >= params.v1)
              ) {
                order.v1 = params.v1;
                order.v2 = params.v2;
                await order.save();
                order = order.get({ plain: true });
                order.a1 = params.a1;
                order.a2 = params.a2;
                order.rate = order.v2 / order.v1;

                broadcast("order", shallow(order));
              } else {
                broadcast("removeOrder", order.id);
                await order.destroy({ transaction });
              }
          } else {
            try {
              await swap(user, params);
            } catch (e) {
              l.warn("Failed to make bid", e.message);
            }
          }
        });
      }
    }, 5000);
  });
}