Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New runtime lifecycle contracts API & Initial Account Deposits (runtime v1.0.0) #188

Merged
merged 14 commits into from
May 11, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions examples/nodejs/src/escrow-flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,14 @@ async function main(action: "buy" | "sell", otherAddress: string, amount: number
console.log("Mediator: " + Mediator);
console.log("Amount: " + amount);

const [contractId, txId] = await runtime.contracts.createContract({
const contractInstance = await runtime.newContractAPI.create({
contract: escrow,
roles: { Buyer, Seller, Mediator },
});

console.log("Contract ID: " + contractId);
console.log("Transaction ID: " + txId);
console.log("Contract ID: " + contractInstance.id);

console.log("Waiting for confirmation...");
await wallet.waitConfirmation(txId);
await contractInstance.waitForConfirmation();
console.log("Contract created successfully!");
}
6 changes: 3 additions & 3 deletions examples/nodejs/src/experimental-features/source-map.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as M from "fp-ts/lib/Map.js";

import { ContractBundleMap, bundleMapToList, isAnnotated, stripAnnotations } from "@marlowe.io/marlowe-object";
import { CreateContractRequestBase, RuntimeLifecycle } from "@marlowe.io/runtime-lifecycle/api";
import { ContractInstanceAPI, CreateContractRequestBase, RuntimeLifecycle } from "@marlowe.io/runtime-lifecycle/api";

import { ContractClosure, getContractClosure } from "./contract-closure.js";
import * as Core from "@marlowe.io/language-core-v1";
Expand Down Expand Up @@ -154,7 +154,7 @@ export interface SourceMap<T> {
closure: ContractClosure;
annotateHistory(history: SingleInputTx[]): SingleInputTx[];
playHistory(history: SingleInputTx[]): TransactionOutput;
createContract(options: CreateContractRequestBase): Promise<[ContractId, TxId]>;
createContract(options: CreateContractRequestBase): Promise<ContractInstanceAPI>;
contractInstanceOf(contractId: ContractId): Promise<boolean>;
}

Expand All @@ -177,7 +177,7 @@ export async function mkSourceMap<T>(
},
createContract: (options: CreateContractRequestBase) => {
const contract = stripAnnotations(closure.contracts.get(closure.main)!);
return lifecycle.contracts.createContract({
return lifecycle.newContractAPI.create({
...options,
contract,
});
Expand Down
42 changes: 20 additions & 22 deletions examples/nodejs/src/marlowe-object-flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@
*/
import { mkLucidWallet, WalletAPI } from "@marlowe.io/wallet";
import { mkRuntimeLifecycle } from "@marlowe.io/runtime-lifecycle";
import { ContractInstanceAPI } from "@marlowe.io/runtime-lifecycle/api";
import { Lucid, Blockfrost, C } from "lucid-cardano";
import { readConfig } from "./config.js";
import { datetoTimeout, When } from "@marlowe.io/language-core-v1";
import {
addressBech32,
contractId,
ContractId,
contractIdToTxId,
stakeAddressBech32,
StakeAddressBech32,
TxId,
Expand Down Expand Up @@ -171,17 +173,17 @@ async function createContractMenu(lifecycle: RuntimeLifecycle, rewardAddress?: S
};
const metadata = delayPaymentTemplate.toMetadata(scheme);
const sourceMap = await mkSourceMap(lifecycle, mkDelayPayment(scheme));
const [contractId, txId] = await sourceMap.createContract({
const contractInstance = await sourceMap.createContract({
stakeAddress: rewardAddress,
tags: { DELAY_PAYMENT_VERSION: "2" },
metadata,
});

console.log(`Contract created with id ${contractId}`);

await waitIndicator(lifecycle.wallet, txId);
await waitIndicator(lifecycle.wallet, contractIdToTxId(contractInstance.id));

return contractMenu(lifecycle, scheme, sourceMap, contractId);
return contractMenu(lifecycle.wallet, contractInstance, scheme, sourceMap);
}

/**
Expand Down Expand Up @@ -213,32 +215,28 @@ async function loadContractMenu(lifecycle: RuntimeLifecycle) {
console.log(` * Amount: ${validationResult.scheme.amount} lovelaces`);
console.log(` * Deposit deadline: ${validationResult.scheme.depositDeadline}`);
console.log(` * Release deadline: ${validationResult.scheme.releaseDeadline}`);

return contractMenu(lifecycle, validationResult.scheme, validationResult.sourceMap, cid);
const contractInstance = await lifecycle.newContractAPI.load(cid);
return contractMenu(lifecycle.wallet, contractInstance, validationResult.scheme, validationResult.sourceMap);
}

/**
* This is an Inquirer.js flow to interact with a contract
*/
async function contractMenu(
lifecycle: RuntimeLifecycle,
wallet: WalletAPI,
contractInstance: ContractInstanceAPI,
scheme: DelayPaymentParameters,
sourceMap: SourceMap<DelayPaymentAnnotations>,
contractId: ContractId
sourceMap: SourceMap<DelayPaymentAnnotations>
): Promise<void> {
// Get and print the contract logical state.
const inputHistory = await lifecycle.contracts.getInputHistory(contractId);

const inputHistory = await contractInstance.getInputHistory();
const contractState = getState(datetoTimeout(new Date()), inputHistory, sourceMap);
if (contractState.type === "Closed") return;

printState(contractState, scheme);

// See what actions are applicable to the current contract state
const { contractDetails, actions } = await lifecycle.applicableActions.getApplicableActions(contractId);

if (contractDetails.type === "closed") return;

const myActionsFilter = await lifecycle.applicableActions.mkFilter(contractDetails);
const myActions = actions.filter(myActionsFilter);
const applicableActions = await contractInstance.evaluateApplicableActions();

const choices: Array<{
name: string;
Expand All @@ -248,7 +246,7 @@ async function contractMenu(
name: "Re-check contract state",
value: { actionType: "check-state" },
},
...myActions.map((action) => {
...applicableActions.myActions.map((action) => {
switch (action.actionType) {
case "Advance":
return {
Expand Down Expand Up @@ -281,19 +279,19 @@ async function contractMenu(
});
switch (selectedAction.actionType) {
case "check-state":
return contractMenu(lifecycle, scheme, sourceMap, contractId);
return contractMenu(wallet, contractInstance, scheme, sourceMap);
case "return":
return;
case "Advance":
case "Deposit":
console.log("Applying input");
const applicableInput = await lifecycle.applicableActions.getInput(contractDetails, selectedAction);
const txId = await lifecycle.applicableActions.applyInput(contractId, {
const applicableInput = await applicableActions.toInput(selectedAction);
const txId = await applicableActions.apply({
input: applicableInput,
});
console.log(`Input applied with txId ${txId}`);
await waitIndicator(lifecycle.wallet, txId);
return contractMenu(lifecycle, scheme, sourceMap, contractId);
await waitIndicator(wallet, txId);
return contractMenu(wallet, contractInstance, scheme, sourceMap);
}
}

Expand Down
19 changes: 11 additions & 8 deletions examples/rest-client-flow/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,13 @@ <h2>Request</h2>
This should be filled with a JSON object that starts with an array, where each element is a numbered
parameter.
</p>
<textarea id="parameter-json" type="text" style="width: 100%; height: 20em">[]</textarea>
<textarea
id="parameter-json"
type="text"
style="width: 100%; height: 20em"
>
{}</textarea
>
</div>
<br />
<input id="healthcheck" type="button" value="Healthcheck" class="endpoint" />
Expand Down Expand Up @@ -148,7 +154,7 @@ <h2>Console</h2>
switch (action) {
case "getContracts":
log(`Getting contracts from ${H.getRuntimeUrl()}`);
result = await restClient.getContracts(...params);
result = await restClient.getContracts(params);
console.log("Contracts", result);
const nextRange = result.nextRange?.value ?? "-";
const prevRange = result.prevRange?.value ?? "-";
Expand All @@ -158,12 +164,12 @@ <h2>Console</h2>
break;
case "submitContract":
log(`Submitting contract on ${H.getRuntimeUrl()}`);
await restClient.submitContract(...getParams());
await restClient.submitContract(getParams());
log(`Done`);
break;
default:
log(`Calling ${action} on ${H.getRuntimeUrl()}`);
result = await restClient[action](...params);
result = await restClient[action](params);
logJSON("Result:", result);
}
} catch (e) {
Expand All @@ -182,10 +188,7 @@ <h2>Console</h2>
try {
params = JSON.parse(jsonParams);
} catch (e) {
throw new Error("Parameters must be a valid JSON array: " + e);
}
if (!Array.isArray(params)) {
throw new Error("Parameters must be an array");
throw new Error("Parameters must be a valid JSON: " + e);
}
return params;
}
Expand Down
8 changes: 6 additions & 2 deletions jsdelivr-npm-importmap.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,16 @@ const importMap = {
"https://cdn.jsdelivr.net/npm/@marlowe.io/[email protected]/dist/bundled/esm/version.js",
"@marlowe.io/language-examples":
"https://cdn.jsdelivr.net/npm/@marlowe.io/[email protected]/dist/bundled/esm/language-examples.js",
"@marlowe.io/language-examples/atomic-swap":
nhenin marked this conversation as resolved.
Show resolved Hide resolved
"https://cdn.jsdelivr.net/npm/@marlowe.io/[email protected]/dist/bundled/esm/atomic-swap.js",
"@marlowe.io/language-specification-client":
"https://cdn.jsdelivr.net/npm/@marlowe.io/[email protected]/dist/bundled/esm/language-specification-client.js",
"@marlowe.io/token-metadata-client":
"https://cdn.jsdelivr.net/npm/@marlowe.io/[email protected]/dist/bundled/esm/token-metadata-client.js",
"@marlowe.io/wallet": "https://cdn.jsdelivr.net/npm/@marlowe.io/[email protected]/dist/bundled/esm/wallet.js",
"@marlowe.io/wallet/api": "https://cdn.jsdelivr.net/npm/@marlowe.io/[email protected]/dist/bundled/esm/api.js",
"@marlowe.io/wallet":
"https://cdn.jsdelivr.net/npm/@marlowe.io/[email protected]/dist/bundled/esm/wallet.js",
"@marlowe.io/wallet/api":
"https://cdn.jsdelivr.net/npm/@marlowe.io/[email protected]/dist/bundled/esm/api.js",
"@marlowe.io/wallet/browser":
"https://cdn.jsdelivr.net/npm/@marlowe.io/[email protected]/dist/bundled/esm/browser.js",
"@marlowe.io/wallet/lucid":
Expand Down
37 changes: 31 additions & 6 deletions packages/adapter/src/io-ts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { Errors } from "io-ts/lib/index.js";
import { Refinement } from "fp-ts/lib/Refinement.js";
import { pipe } from "fp-ts/lib/function.js";
import * as Either from "fp-ts/lib/Either.js";
import * as BigIntReporter from "jsonbigint-io-ts-reporters";

/**
* In the TS-SDK we duplicate the type and guard definition for each type as the
* inferred type from io-ts does not produce a good type export when used with
Expand Down Expand Up @@ -88,20 +90,43 @@ export function expectType<T>(guard: t.Type<T>, aValue: unknown): T {
}

/**
* A mechanism for validating the type of a strict in a dynamically type context.
* @param strict Whether to perform runtime checking to provide helpful error messages. May have a slight negative performance impact.
* Formats validation errors into a string.
* @param errors - The validation errors to format.
* @returns A string representation of the validation errors.
*/
export function strictDynamicTypeCheck(strict: unknown): strict is boolean {
return typeof strict === "boolean";
export function formatValidationErrors(errors: Errors): string {
return BigIntReporter.formatValidationErrors(errors, {
truncateLongTypes: true,
}).join("\n");
}

export function dynamicAssertType<G extends t.Any>(
guard: G,
value: unknown,
message?: string
): t.TypeOf<G> {
const result = guard.decode(value);
if (Either.isLeft(result)) {
throw new InvalidTypeError(guard, value, result.left, message);
}
return result.right;
}

/**
* This error is thrown when we are dynamicly checking for the type of a value and the type is not
* the expected one.
*/
export class InvalidTypeError extends Error {
constructor(
public readonly guard: t.Any,
public readonly value: unknown,
public readonly errors: Errors,
public readonly value: any,
message?: string
) {
super(message);
const msg =
message ??
`Unexpected type for value:\n${formatValidationErrors(errors)}`;
super(msg);
}
}

Expand Down
8 changes: 4 additions & 4 deletions packages/language/core/v1/src/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const mkEnvironment =
});

/**
* TODO: Comment
* Time interval in which the contract is executed. It is defined by a start and end time. The time is represented as a POSIX time.
* @see Appendix E.16 of the {@link https://github.com/input-output-hk/marlowe/releases/download/v3/Marlowe.pdf | Marlowe specification}
* @category Environment
*/
Expand All @@ -22,7 +22,7 @@ export interface TimeInterval {
}

/**
* TODO: Comment
* Guard for {@link TimeInterval}
* @see Appendix E.16 of the {@link https://github.com/input-output-hk/marlowe/releases/download/v3/Marlowe.pdf | Marlowe specification}
* @category Environment
*/
Expand All @@ -32,7 +32,7 @@ export const TimeIntervalGuard: t.Type<TimeInterval> = t.type({
});

/**
* TODO: Comment
* Time interval in which the contract is executed.
* @see Section 2.1.10 and appendix E.22 of the {@link https://github.com/input-output-hk/marlowe/releases/download/v3/Marlowe.pdf | Marlowe specification}
* @category Environment
*/
Expand All @@ -41,7 +41,7 @@ export interface Environment {
}

/**
* TODO: Comment
* Guard for {@link Environment}
* @see Section 2.1.10 and appendix E.22 of the {@link https://github.com/input-output-hk/marlowe/releases/download/v3/Marlowe.pdf | Marlowe specification}
* @category Environment
*/
Expand Down
Loading
Loading