Skip to content

Commit

Permalink
feat: invoke with tickets
Browse files Browse the repository at this point in the history
  • Loading branch information
aguillon committed Nov 30, 2022
1 parent a5912d4 commit 4806b69
Show file tree
Hide file tree
Showing 11 changed files with 118 additions and 22 deletions.
17 changes: 13 additions & 4 deletions deku-c/client/src/deku-c/contract.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { DekuCClient } from ".";
import { DekuPClient } from "../deku-p/index";
import Balances, { Balances as BalancesType } from "../deku-p/core/balances";
import { compileExpression, compileLigoExpression } from "./utils";

export type JSONType =
Expand Down Expand Up @@ -108,21 +109,25 @@ export class Contract {
* @param parameter the parameter of the contract as provided by tunac
* @returns the hash of the operation
*/
async invokeRaw(parameter: any): Promise<string> {
async invokeRaw(parameter: any, tickets?: BalancesType): Promise<string> {
if (tickets === undefined) tickets = [];

const invoke = {
operation: JSON.stringify({
address: this.address,
argument: parameter,
}),
tickets: [],
tickets,
};
const hash = await this.deku.submitVmOperation(invoke);
return hash;
}

async invoke(expression: string): Promise<string> {
async invoke(expression: string, tickets?: BalancesType): Promise<string> {
if (!tickets) tickets = [];
const parameter = { expression, address: this.address };
const invoke = await compileExpression(this.deku.dekuRpc, parameter);
invoke.tickets = Balances.toDTO(tickets);
const hash = await this.deku.submitVmOperation(invoke);
return hash;
}
Expand All @@ -132,7 +137,11 @@ export class Contract {
* @param parameter the parameter of the contract, in Ligo // FIXME lang
* @returns the hash of the operation
*/
async invokeLigo(kind: ligo_kind, code: string, expression: string): Promise<string> {
async invokeLigo(
kind: ligo_kind,
code: string,
expression: string
): Promise<string> {
// FIXME the need for the two RPCs stinks (also they're strings)
const parameter = {
kind,
Expand Down
1 change: 0 additions & 1 deletion deku-c/client/src/deku-c/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export type Settings = {
export class DekuCClient extends DekuPClient {
readonly ligoRpc?: string;


constructor(settings: Settings) {
super(settings);
this.ligoRpc = settings.ligoRpc;
Expand Down
11 changes: 9 additions & 2 deletions deku-c/client/src/deku-c/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { JSONType } from "./contract";
import Balances, { Balances as BalancesType } from "../deku-p/core/balances";
import * as path from "path";

export const originateTz = async (
Expand Down Expand Up @@ -35,7 +36,10 @@ export const originateLigo = async (
method: "POST",
body: JSON.stringify({ lang: kind, source: code }),
};
const result = await fetch(path.join(ligoRpc, "/api/v1/ligo/originate"), options);
const result = await fetch(
path.join(ligoRpc, "/api/v1/ligo/originate"),
options
);
const { code: source } = await result.json();
return originateTz(dekuRpc, { code: source, initialStorage });
}
Expand Down Expand Up @@ -88,7 +92,10 @@ export const compileLigoExpression = async (
expression: ligoExpression,
}),
};
const result = await fetch(path.join(ligoRpc, "/api/v1/ligo/expression"), options);
const result = await fetch(
path.join(ligoRpc, "/api/v1/ligo/expression"),
options
);
const { expression } = await result.json();
return compileExpression(dekuRpc, { expression, address });
}
Expand Down
20 changes: 20 additions & 0 deletions deku-c/client/src/deku-p/core/address.ts
Original file line number Diff line number Diff line change
@@ -1 +1,21 @@
import { validateKeyHash, validateContractAddress } from "@taquito/utils";

export type Address = string;

const parseAddress = (s: string): Address => {
if (s[0] === '"') {
if (!(s[s.length - 1] === '"')) throw Error(`Ill-formed address: ${s}`);
s = s.slice(1, -1);
}

// TODO: check that the address is correct for Deku
if (s.slice(0, 2) === "DK") return s;

if (validateKeyHash(s) || validateContractAddress(s)) return s;

throw Error(`Invalid address ${s}`);
};

export default {
parseAddress,
};
27 changes: 27 additions & 0 deletions deku-c/client/src/deku-p/core/balances.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Amount, { Amount as AmountType } from "./amount";
import JSONValue, { JSONType } from "../utils/json";
import TicketID, { TicketID as TicketIDType } from "./ticket-id";

Expand All @@ -23,6 +24,32 @@ const ofDTO = (json: JSONValue): Balances | null => {
return balances;
};

const toDTO = (balances: Balances) => {
const DTO = balances.map((tamount) => {
const ticket = TicketID.toDTO(tamount.ticket);
const amount = tamount.amount.toString(); // FIXME please help
return [ticket, amount];
});
return DTO;
};

const parseTicketAmount = (s: string): TicketAmount => {
if (s[0] === "(") {
if (!(s[s.length - 1] === ")")) throw Error(`Ill-formed pair: ${s}`);
s = s.slice(1, -1);
}
const parts = s.split(" ").filter((x) => x);
let i = 0;
if (parts[0] == "Pair") i = 1;

const ticketID = TicketID.parseTicketID(parts[i] + " " + parts[i + 1]);
const amount = parseInt(parts[i + 2]);
if (amount) return { ticket: ticketID, amount };
else throw Error(`Incorrect amount: ${parts[i + 2]}`);
};

export default {
ofDTO,
toDTO,
parseTicketAmount,
};
27 changes: 21 additions & 6 deletions deku-c/client/src/deku-p/core/ticket-id.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import JSONValue, { JSONType } from "../utils/json";
import Address, { Address as AddressType } from "./address";

export type TicketID = {
ticketer: string;
ticketer: AddressType;
data: string;
};

Expand All @@ -25,18 +26,32 @@ const ofDTO = (json: JSONValue): TicketID | null => {
return { ticketer, data };
};

const ofString = (str: String): TicketID | null => {
const split = str.split(" ");
const toDTO = (ticket: TicketID) => {
let data = ticket.data;
if (data.startsWith("0x")) data = data.slice(2);

return [
"Ticket_id",
{
ticketer: ticket.ticketer,
data: data,
},
];
};

const parseTicketID = (str: String): TicketID => {
const split = str.split(" ").filter((x) => x);
if (split.length != 2) {
throw Error(`Incorrect argument for TicketID: ${str}`);
}

// TODO test ticketer and data are valid
return { ticketer: split[0], data: split[1] };
// TODO test that data is valid
return { ticketer: Address.parseAddress(split[0]), data: split[1] };
};

export default {
createTicketID,
ofDTO,
ofString,
toDTO,
parseTicketID,
};
6 changes: 3 additions & 3 deletions deku-c/client/src/deku-p/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -357,14 +357,14 @@ export class DekuPClient {
return this.submitOperation(noopOperation);
}

async wait(operationHash: OperationHashType): Promise<LevelType> {
console.log(operationHash);
async wait(_operationHash: OperationHashType): Promise<LevelType> {
throw "Feature not yet implemented"; // TODO: implement this feature
}
}

export const parseTicketID = TicketID.ofString;
export const parseTicketID = TicketID.parseTicketID;
export const makeTicketID = TicketID.createTicketID;
export const parseTicketAmount = Balances.parseTicketAmount;
// TODO export type too?

export {
Expand Down
1 change: 1 addition & 0 deletions deku-c/client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ export {
fromMemorySigner,
parseTicketID,
makeTicketID,
parseTicketAmount,
} from "./deku-p";
export { DekuCClient, Contract } from "./deku-c";
2 changes: 1 addition & 1 deletion deku-c/client/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"include": ["src/index.ts",],
"include": ["src/index.ts"],
"exclude": ["node_modules", "**/*.spec.ts"],
"compilerOptions": {
"outDir": "dist",
Expand Down
26 changes: 22 additions & 4 deletions deku-c/deku-cli/commands/invoke.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { fromMemorySigner } from "@marigold-dev/deku";
import { InMemorySigner } from "@taquito/signer";
import { Contract, DekuCClient } from "@marigold-dev/deku";
import { Contract, DekuCClient, parseTicketAmount } from "@marigold-dev/deku";
import { load } from "../core/wallet";
import * as Commander from "commander";
import { read, isLigo } from "../core/contract";
Expand All @@ -17,21 +17,28 @@ function getContract(apiUri, walletPath, contractAddress, ligoUri?) {
return deku.contract(contractAddress);
}

function parseTicketAmounts(args: string[]) {
return args.map((str) => {
return parseTicketAmount(str);
});
}

async function invokeMain(
apiUri,
walletPath,
contractAddress,
parameter,
ticketAmounts,
options
) {
try {
const contract = getContract(apiUri, walletPath, contractAddress);
if (options.raw !== undefined) {
const parameter_parsed = JSON.parse(parameter);
const hash = await contract.invokeRaw(parameter);
const hash = await contract.invokeRaw(parameter, ticketAmounts);
console.log("Operation hash:", hash);
} else {
const hash = await contract.invoke(parameter);
const hash = await contract.invoke(parameter, ticketAmounts);
console.log("operation hash:", hash);
}
} catch (e) {
Expand Down Expand Up @@ -88,8 +95,19 @@ export default function make(command: Commander.Command) {
`URI of the deku API to use (default ${default_.api})`
)
.action((walletPath, contractAddress, parameter, options) => {
const unparsedArguments = invoke.args.slice(3);
console.log("UNPARSED:", unparsedArguments);
const apiUri = options.endpoint ?? default_.api;
invokeMain(apiUri, walletPath, contractAddress, parameter, options);
const tickets = parseTicketAmounts(unparsedArguments);

invokeMain(
apiUri,
walletPath,
contractAddress,
parameter,
tickets,
options
);
});

invokeLigo
Expand Down
2 changes: 1 addition & 1 deletion deku-c/deku-cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
make_show_balance,
} from "./commands";

process.removeAllListeners('warning');
process.removeAllListeners("warning");

const program = new Commander.Command();

Expand Down

0 comments on commit 4806b69

Please sign in to comment.