golemfactory / yagna-docs

Documentation for yagna
GNU General Public License v3.0
4 stars 3 forks source link

Mid-level API tutorial #157

Closed mgordel closed 1 year ago

mgordel commented 1 year ago

Tutorial and description of mid-level components. An example demonstrating the use of the Mid-level API:


async function main() {
  const taskPackage = await Package.create({ imageHash });
  const allocation = await Allocation.create({ account, logger });
  const demand = await Demand.create(taskPackage, [allocation], { subnetTag, logger });
  const offer: Proposal = await new Promise((res) =>
    demand.addEventListener(DemandEventType, async (event) => {
      const proposalEvent = event as DemandEvent;
      if (proposalEvent.proposal.isInitial()) await proposalEvent.proposal.respond(account.platform);
      else if (proposalEvent.proposal.isDraft()) res(proposalEvent.proposal);
    })
  );
  const agreement = await Agreement.create(offer.id, { logger });
  await agreement.confirm();
  const activity = await Activity.create(agreement.id, { logger });
  const script = await Script.create([new Deploy(), new Start(), new Run("/bin/sh", ["-c", "echo 'Hello Golem'"])]);
  const exeScript = script.getExeScriptRequest();
  const streamResult = await activity.execute(exeScript);
  const results: Result[] = [];
  for await (const result of streamResult) results.push(result);
  console.log(results[2].stdout);
  await activity.stop();
  await agreement.terminate();
  await allocation.release();
  await demand.unsubscribe();
}