"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const bn_js_1 = __importDefault(require("bn.js"));
const logging_1 = require("../src/logging");
const log = logging_1.factory.getLogger("scripts.submitSolution");
const BatchExchange = artifacts.require("BatchExchange");
const argv = require("yargs")
    .option("resultFile", {
    describe: "The path to the solver's solution file",
})
    .demand(["resultFile"])
    .help(false)
    .version(false).argv;
// Turns T00x to x
const tokenID = (t) => parseInt(t.slice(1));
module.exports = (callback) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const instance = yield BatchExchange.deployed();
        const batchId = (yield instance.getCurrentBatchId()).subn(1);
        const result = require(argv.resultFile);
        // Extract traded amounts
        const owners = [];
        const orderIds = [];
        const buyVolumes = [];
        result.orders.forEach((order) => {
            owners.push(order.accountID);
            orderIds.push(new bn_js_1.default(order.orderID));
            buyVolumes.push(new bn_js_1.default(order.execBuyAmount));
        });
        //Extract prices
        const prices = [];
        const tokenIdsForPrice = [];
        for (const token in result.prices) {
            const id = tokenID(token);
            if (id == 0) {
                continue;
            }
            prices.push(new bn_js_1.default(result.prices[token]));
            tokenIdsForPrice.push(id);
        }
        // Cannot be U256::max because the SC would otherwise overflow
        const objectiveValue = new bn_js_1.default(2).shln(248).subn(1);
        log.info(`Submitting solution for batch ${batchId} with args:
      objective: ${objectiveValue}
      owners: [${owners}]
      orderIds: [${orderIds}]
      buyVolumes: [${buyVolumes}]
      prices: [${prices}]
      tokenIdsForPrice: [${tokenIdsForPrice}]
    `);
        yield instance.submitSolution(batchId, objectiveValue, owners, orderIds, buyVolumes, prices, tokenIdsForPrice);
    }
    catch (error) {
        callback(error);
    }
});
