/* eslint no-console:"off" */

/**
 * This script demonstrates how to transfer tokens between 2 accounts
 *
 * Run script with: `DEBUG=@ocap/client node examples/transfer_token.js`
 */

const { fromRandom } = require('@ocap/wallet');
const GraphQLClient = require('../lib/node');

const endpoint = process.env.OCAP_API_HOST || 'http://127.0.0.1:4000'; // testnet

const client = new GraphQLClient(`${endpoint}/api`);
const sleep = (timeout) =>
  new Promise((resolve) => {
    setTimeout(resolve, timeout);
  });

(async () => {
  try {
    const sender = fromRandom();
    const receiver = fromRandom();
    console.log({ sender: sender.address, receiver: receiver.address });

    // 1. Declare sender
    let hash = await client.declare({ moniker: 'sender', wallet: sender });
    console.log('sender declare tx', `${endpoint}/explorer/txs/${hash}`);
    console.log('sender account', `${endpoint}/explorer/accounts/${sender.address}`);

    // 2. Declare receiver
    hash = await client.declare({ moniker: 'receiver', wallet: receiver });
    console.log('receiver declare tx', `${endpoint}/explorer/txs/${hash}`);
    console.log('receiver account', `${endpoint}/explorer/accounts/${receiver.address}`);

    await sleep(3000);

    // 3. Poke for sender
    hash = await client.checkin({ wallet: sender });
    console.log('sender poke tx', `${endpoint}/explorer/txs/${hash}`);

    // 4. Poke for receiver
    hash = await client.checkin({ wallet: receiver });
    console.log('receiver poke tx', `${endpoint}/explorer/txs/${hash}`);

    await sleep(3000);

    // 5. Transfer token
    hash = await client.transfer({
      to: receiver.address,
      token: 10,
      memo: 'this is the transfer note',
      wallet: sender,
    });
    console.log('view transfer tx', `${endpoint}/explorer/txs/${hash}`);
  } catch (err) {
    console.error(err);
    console.log(JSON.stringify(err.errors));
  }
})();
