Compare commits
3 Commits
main
...
85746c3306
| Author | SHA1 | Date | |
|---|---|---|---|
|
85746c3306
|
|||
|
def261b568
|
|||
|
3d6518e465
|
48
package-lock.json
generated
48
package-lock.json
generated
@@ -17,6 +17,7 @@
|
|||||||
"@xo-cash/state": "file:../state",
|
"@xo-cash/state": "file:../state",
|
||||||
"@xo-cash/templates": "file:../templates",
|
"@xo-cash/templates": "file:../templates",
|
||||||
"@xo-cash/types": "^0.0.1",
|
"@xo-cash/types": "^0.0.1",
|
||||||
|
"@xo-cash/utils": "file:../utils",
|
||||||
"better-sqlite3": "^12.6.2",
|
"better-sqlite3": "^12.6.2",
|
||||||
"clipboardy": "^5.1.0",
|
"clipboardy": "^5.1.0",
|
||||||
"ink": "^6.6.0",
|
"ink": "^6.6.0",
|
||||||
@@ -47,16 +48,16 @@
|
|||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@bitauth/libauth": "^3.1.0-next.8",
|
"@bitauth/libauth": "^3.1.0-next.8",
|
||||||
"@electrum-cash/application": "^0.2.3-development.13424909069",
|
"@electrum-cash/application": "^0.2.3-development.13447192992",
|
||||||
"@electrum-cash/network": "^4.2.2",
|
"@electrum-cash/network": "^4.2.2",
|
||||||
"@electrum-cash/protocol": "^2.3.1",
|
"@electrum-cash/protocol": "^2.3.1",
|
||||||
"@electrum-cash/servers": "^3.1.0",
|
"@electrum-cash/servers": "^3.1.0",
|
||||||
"@xo-cash/crypto": "file:../crypto",
|
"@xo-cash/crypto": "0.0.1",
|
||||||
"@xo-cash/primitives": "0.0.1",
|
"@xo-cash/primitives": "file:../primitives",
|
||||||
"@xo-cash/state": "0.0.2",
|
"@xo-cash/state": "file:../state",
|
||||||
"@xo-cash/templates": "0.0.1",
|
"@xo-cash/templates": "0.0.1",
|
||||||
"@xo-cash/types": "0.0.1",
|
"@xo-cash/types": "^0.0.1-development.14519184304",
|
||||||
"@xo-cash/utils": "0.0.1",
|
"@xo-cash/utils": "^0.0.1-development.14519184505",
|
||||||
"eventemitter3": "^5.0.1"
|
"eventemitter3": "^5.0.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -140,6 +141,37 @@
|
|||||||
"vitest": "^4.0.17"
|
"vitest": "^4.0.17"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"../utils": {
|
||||||
|
"name": "@xo-cash/utils",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@bitauth/libauth": "^3.1.0-next.8",
|
||||||
|
"@xo-cash/types": "0.0.1",
|
||||||
|
"zod": "^4.3.6"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@chalp/eslint-airbnb": "^1.3.0",
|
||||||
|
"@generalprotocols/cspell-dictionary": "^1.0.1",
|
||||||
|
"@stylistic/eslint-plugin": "^5.7.0",
|
||||||
|
"@types/node": "^25.5.0",
|
||||||
|
"@typescript-eslint/eslint-plugin": "^8.53.1",
|
||||||
|
"@typescript-eslint/parser": "^8.53.1",
|
||||||
|
"@vitest/coverage-v8": "^4.0.17",
|
||||||
|
"@viz-kit/esbuild-analyzer": "^1.0.0",
|
||||||
|
"@xo-cash/eslint-config": "1.0.1",
|
||||||
|
"@xo-cash/templates": "0.0.1",
|
||||||
|
"cspell": "^9.6.0",
|
||||||
|
"eslint": "^9.39.2",
|
||||||
|
"prettier": "^3.6.2",
|
||||||
|
"tsdown": "^0.20.0-beta.4",
|
||||||
|
"typedoc": "^0.28.16",
|
||||||
|
"typedoc-plugin-coverage": "^4.0.2",
|
||||||
|
"typescript": "^5.3.2",
|
||||||
|
"typescript-eslint": "^8.53.1",
|
||||||
|
"vitest": "^4.0.17"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@alcalzone/ansi-tokenize": {
|
"node_modules/@alcalzone/ansi-tokenize": {
|
||||||
"version": "0.2.4",
|
"version": "0.2.4",
|
||||||
"resolved": "https://registry.npmjs.org/@alcalzone/ansi-tokenize/-/ansi-tokenize-0.2.4.tgz",
|
"resolved": "https://registry.npmjs.org/@alcalzone/ansi-tokenize/-/ansi-tokenize-0.2.4.tgz",
|
||||||
@@ -977,6 +1009,10 @@
|
|||||||
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
|
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@xo-cash/utils": {
|
||||||
|
"resolved": "../utils",
|
||||||
|
"link": true
|
||||||
|
},
|
||||||
"node_modules/ansi-escapes": {
|
"node_modules/ansi-escapes": {
|
||||||
"version": "7.2.0",
|
"version": "7.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.2.0.tgz",
|
||||||
|
|||||||
@@ -41,6 +41,7 @@
|
|||||||
"@xo-cash/state": "file:../state",
|
"@xo-cash/state": "file:../state",
|
||||||
"@xo-cash/templates": "file:../templates",
|
"@xo-cash/templates": "file:../templates",
|
||||||
"@xo-cash/types": "^0.0.1",
|
"@xo-cash/types": "^0.0.1",
|
||||||
|
"@xo-cash/utils": "file:../utils",
|
||||||
"better-sqlite3": "^12.6.2",
|
"better-sqlite3": "^12.6.2",
|
||||||
"clipboardy": "^5.1.0",
|
"clipboardy": "^5.1.0",
|
||||||
"ink": "^6.6.0",
|
"ink": "^6.6.0",
|
||||||
|
|||||||
@@ -34,8 +34,8 @@ import { homedir } from "node:os";
|
|||||||
*
|
*
|
||||||
* IMPORTANT: Keep this in sync with actual switch statements in command handlers:
|
* IMPORTANT: Keep this in sync with actual switch statements in command handlers:
|
||||||
* - mnemonic.ts: create, import, list, expose
|
* - mnemonic.ts: create, import, list, expose
|
||||||
* - template.ts: import, list, inspect, set-default
|
* - template.ts: import, list, inspect, export, set-default
|
||||||
* - invitation.ts: create, append, sign, broadcast, requirements, import, inspect, list
|
* - invitation.ts: create, append, sign, broadcast, requirements, import, export, inspect, list
|
||||||
* - resource.ts: list, unreserve, unreserve-all
|
* - resource.ts: list, unreserve, unreserve-all
|
||||||
* - settings.ts: show, get, set
|
* - settings.ts: show, get, set
|
||||||
*/
|
*/
|
||||||
@@ -43,7 +43,7 @@ import { homedir } from "node:os";
|
|||||||
/** Subcommands for the mnemonic command */
|
/** Subcommands for the mnemonic command */
|
||||||
const MNEMONIC_SUBS = ["create", "import", "list", "expose"];
|
const MNEMONIC_SUBS = ["create", "import", "list", "expose"];
|
||||||
/** Subcommands for the template command */
|
/** Subcommands for the template command */
|
||||||
const TEMPLATE_SUBS = ["import", "list", "inspect", "set-default"];
|
const TEMPLATE_SUBS = ["import", "list", "inspect", "export", "set-default"];
|
||||||
/** Subcommands for the invitation command */
|
/** Subcommands for the invitation command */
|
||||||
const INVITATION_SUBS = [
|
const INVITATION_SUBS = [
|
||||||
"create",
|
"create",
|
||||||
@@ -52,6 +52,7 @@ const INVITATION_SUBS = [
|
|||||||
"broadcast",
|
"broadcast",
|
||||||
"requirements",
|
"requirements",
|
||||||
"import",
|
"import",
|
||||||
|
"export",
|
||||||
"inspect",
|
"inspect",
|
||||||
"list",
|
"list",
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -8,11 +8,7 @@
|
|||||||
* and instead constructs the engine directly with an in-memory blockchain provider.
|
* and instead constructs the engine directly with an in-memory blockchain provider.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import {
|
import { BlockchainMonitor, Engine } from "@xo-cash/engine";
|
||||||
BlockchainMonitor,
|
|
||||||
Engine,
|
|
||||||
InMemoryBlockchainProvider,
|
|
||||||
} from "@xo-cash/engine";
|
|
||||||
import { createStorageAdapter, State, StorageType } from "@xo-cash/state";
|
import { createStorageAdapter, State, StorageType } from "@xo-cash/state";
|
||||||
import { convertMnemonicToSeedBytes } from "@xo-cash/crypto";
|
import { convertMnemonicToSeedBytes } from "@xo-cash/crypto";
|
||||||
import { binToHex, hash256 } from "@bitauth/libauth";
|
import { binToHex, hash256 } from "@bitauth/libauth";
|
||||||
@@ -67,18 +63,21 @@ export async function createOfflineEngine(
|
|||||||
// Create the state instance
|
// Create the state instance
|
||||||
const state = new State(storageAdapter);
|
const state = new State(storageAdapter);
|
||||||
|
|
||||||
// Use in-memory blockchain provider (no network connections)
|
// Create a minimal blockchain monitor (no electrum initialization)
|
||||||
const blockchainProvider = new InMemoryBlockchainProvider();
|
const blockchainMonitor = new BlockchainMonitor(state);
|
||||||
await blockchainProvider.initialize({
|
|
||||||
applicationIdentifier: "xo-cli-completions",
|
|
||||||
electrumOptions: {},
|
|
||||||
});
|
|
||||||
|
|
||||||
// Create a minimal blockchain monitor
|
// Engine constructor is private; bypass for offline read-only completions.
|
||||||
const blockchainMonitor = new BlockchainMonitor(state, blockchainProvider);
|
type EngineConstructor = new (
|
||||||
|
mnemonic: string,
|
||||||
|
state: State,
|
||||||
|
blockchainMonitor: BlockchainMonitor,
|
||||||
|
) => Engine;
|
||||||
|
|
||||||
// Construct engine directly without state sync
|
const engine = new (Engine as unknown as EngineConstructor)(
|
||||||
const engine = new Engine(seed, state, blockchainMonitor, blockchainProvider);
|
seed,
|
||||||
|
state,
|
||||||
|
blockchainMonitor,
|
||||||
|
);
|
||||||
|
|
||||||
return engine;
|
return engine;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -161,7 +161,7 @@ _{{FUNC_NAME}}_completions() {
|
|||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
;;
|
;;
|
||||||
append|sign|broadcast|requirements|inspect)
|
append|sign|broadcast|requirements|export|inspect)
|
||||||
# These subcommands expect an invitation identifier as first arg.
|
# These subcommands expect an invitation identifier as first arg.
|
||||||
local pos=$((cword - subcmd_idx))
|
local pos=$((cword - subcmd_idx))
|
||||||
if [[ $pos -eq 1 ]]; then
|
if [[ $pos -eq 1 ]]; then
|
||||||
|
|||||||
@@ -70,6 +70,7 @@ complete -c {{BIN_NAME}} -n "__fish_seen_subcommand_from invitation; and __fish_
|
|||||||
complete -c {{BIN_NAME}} -n "__fish_seen_subcommand_from invitation; and __fish_seen_subcommand_from sign; and test (count (commandline -opc)) -eq 3" -xa '(__{{FUNC_NAME}}_complete_dynamic invitations)'
|
complete -c {{BIN_NAME}} -n "__fish_seen_subcommand_from invitation; and __fish_seen_subcommand_from sign; and test (count (commandline -opc)) -eq 3" -xa '(__{{FUNC_NAME}}_complete_dynamic invitations)'
|
||||||
complete -c {{BIN_NAME}} -n "__fish_seen_subcommand_from invitation; and __fish_seen_subcommand_from broadcast; and test (count (commandline -opc)) -eq 3" -xa '(__{{FUNC_NAME}}_complete_dynamic invitations)'
|
complete -c {{BIN_NAME}} -n "__fish_seen_subcommand_from invitation; and __fish_seen_subcommand_from broadcast; and test (count (commandline -opc)) -eq 3" -xa '(__{{FUNC_NAME}}_complete_dynamic invitations)'
|
||||||
complete -c {{BIN_NAME}} -n "__fish_seen_subcommand_from invitation; and __fish_seen_subcommand_from requirements; and test (count (commandline -opc)) -eq 3" -xa '(__{{FUNC_NAME}}_complete_dynamic invitations)'
|
complete -c {{BIN_NAME}} -n "__fish_seen_subcommand_from invitation; and __fish_seen_subcommand_from requirements; and test (count (commandline -opc)) -eq 3" -xa '(__{{FUNC_NAME}}_complete_dynamic invitations)'
|
||||||
|
complete -c {{BIN_NAME}} -n "__fish_seen_subcommand_from invitation; and __fish_seen_subcommand_from export; and test (count (commandline -opc)) -eq 3" -xa '(__{{FUNC_NAME}}_complete_dynamic invitations)'
|
||||||
complete -c {{BIN_NAME}} -n "__fish_seen_subcommand_from invitation; and __fish_seen_subcommand_from inspect; and test (count (commandline -opc)) -eq 3" -xa '(__{{FUNC_NAME}}_complete_dynamic invitations)'
|
complete -c {{BIN_NAME}} -n "__fish_seen_subcommand_from invitation; and __fish_seen_subcommand_from inspect; and test (count (commandline -opc)) -eq 3" -xa '(__{{FUNC_NAME}}_complete_dynamic invitations)'
|
||||||
|
|
||||||
# invitation import <path>
|
# invitation import <path>
|
||||||
|
|||||||
@@ -145,7 +145,7 @@ _{{FUNC_NAME}}_completions() {
|
|||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
;;
|
;;
|
||||||
append|sign|broadcast|requirements|inspect)
|
append|sign|broadcast|requirements|export|inspect)
|
||||||
# These subcommands take invitation ID as first argument.
|
# These subcommands take invitation ID as first argument.
|
||||||
local pos=$((CURRENT - subcmd_idx))
|
local pos=$((CURRENT - subcmd_idx))
|
||||||
if [[ $pos -eq 1 ]]; then
|
if [[ $pos -eq 1 ]]; then
|
||||||
|
|||||||
@@ -11,13 +11,21 @@ import {
|
|||||||
resolveProvidedLockingBytecodeHex,
|
resolveProvidedLockingBytecodeHex,
|
||||||
mapUnspentOutputsToSelectable,
|
mapUnspentOutputsToSelectable,
|
||||||
autoSelectGreedyUtxos,
|
autoSelectGreedyUtxos,
|
||||||
|
hasMissingRequirements,
|
||||||
} from "../../utils/invitation-flow.js";
|
} from "../../utils/invitation-flow.js";
|
||||||
import { encodeExtendedJson } from "../../utils/ext-json.js";
|
import { deserializeInvitation, serializeInvitation } from "@xo-cash/engine";
|
||||||
|
import type { XOInvitation } from "@xo-cash/types";
|
||||||
import { resolveTemplate } from "../utils.js";
|
import { resolveTemplate } from "../utils.js";
|
||||||
|
|
||||||
const DEFAULT_FEE = 500n;
|
const DEFAULT_FEE = 500n;
|
||||||
const DUST_THRESHOLD = 546n;
|
const DUST_THRESHOLD = 546n;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Serializes an invitation to pretty-printed JSON for file export.
|
||||||
|
*/
|
||||||
|
const formatInvitationForFile = (invitation: XOInvitation, indent = 2): string =>
|
||||||
|
JSON.stringify(JSON.parse(serializeInvitation(invitation)), null, indent);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Result of parsing CLI options into inputs and outputs for an append call.
|
* Result of parsing CLI options into inputs and outputs for an append call.
|
||||||
* A `null` return signals a fatal error that was already logged to stderr.
|
* A `null` return signals a fatal error that was already logged to stderr.
|
||||||
@@ -286,9 +294,13 @@ ${bold("Sub-commands:")}
|
|||||||
- broadcast <invitation-id> ${dim("Broadcast an invitation")}
|
- broadcast <invitation-id> ${dim("Broadcast an invitation")}
|
||||||
- requirements <invitation-id> ${dim("Show requirements for an invitation")}
|
- requirements <invitation-id> ${dim("Show requirements for an invitation")}
|
||||||
- import <invitation-file> ${dim("Import an invitation from a file")}
|
- import <invitation-file> ${dim("Import an invitation from a file")}
|
||||||
|
- export <invitation-id> [output-file] ${dim("Export an invitation to stdout or a file")}
|
||||||
- inspect <invitation-id | invitation-file> ${dim("Inspect an invitation")}
|
- inspect <invitation-id | invitation-file> ${dim("Inspect an invitation")}
|
||||||
- list ${dim("List all invitations")}
|
- list ${dim("List all invitations")}
|
||||||
|
|
||||||
|
${bold("Export options:")}
|
||||||
|
-o --output <output-filename> ${dim("Output filename for the exported invitation")}
|
||||||
|
|
||||||
${bold("Create / Append options:")}
|
${bold("Create / Append options:")}
|
||||||
-var-<name> <value> ${dim("Set a variable (e.g. -var-requested-satoshis 1000)")}
|
-var-<name> <value> ${dim("Set a variable (e.g. -var-requested-satoshis 1000)")}
|
||||||
--add-input <txhash:vout> ${dim("Add UTXO input(s), comma-separated (e.g. abc123:0,def456:1)")}
|
--add-input <txhash:vout> ${dim("Add UTXO input(s), comma-separated (e.g. abc123:0,def456:1)")}
|
||||||
@@ -311,6 +323,7 @@ export type InvitationCommandResult = {
|
|||||||
invitationIdentifier?: string;
|
invitationIdentifier?: string;
|
||||||
txHash?: string;
|
txHash?: string;
|
||||||
count?: number;
|
count?: number;
|
||||||
|
outputFile?: string;
|
||||||
templateName?: string;
|
templateName?: string;
|
||||||
actionIdentifier?: string;
|
actionIdentifier?: string;
|
||||||
status?: string;
|
status?: string;
|
||||||
@@ -320,6 +333,66 @@ export type InvitationCommandResult = {
|
|||||||
variables?: unknown[];
|
variables?: unknown[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles the invitation export command.
|
||||||
|
* Throws CommandError on failure, returns result data on success.
|
||||||
|
* @param deps - The command dependencies.
|
||||||
|
* @param args - Positional args after "export", e.g. ["invitation-id"] or ["invitation-id", "invitation.json"].
|
||||||
|
* @param options - Parsed option flags.
|
||||||
|
*/
|
||||||
|
export const handleInvitationExportCommand = async (
|
||||||
|
deps: CommandDependencies,
|
||||||
|
args: string[],
|
||||||
|
options: Record<string, string>,
|
||||||
|
): Promise<{ invitationIdentifier?: string; outputFile?: string }> => {
|
||||||
|
const invitationIdentifier = args[0];
|
||||||
|
deps.io.verbose(`Invitation identifier: ${invitationIdentifier}`);
|
||||||
|
|
||||||
|
if (!invitationIdentifier) {
|
||||||
|
deps.io.verbose("No invitation identifier provided");
|
||||||
|
printInvitationHelp(deps.io);
|
||||||
|
throw new CommandError(
|
||||||
|
"invitation.export.identifier_missing",
|
||||||
|
"No invitation identifier provided",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const invitation = deps.app.invitations.find(
|
||||||
|
(candidate) =>
|
||||||
|
candidate.data.invitationIdentifier === invitationIdentifier,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!invitation) {
|
||||||
|
deps.io.err(`Invitation not found: ${invitationIdentifier}`);
|
||||||
|
throw new CommandError(
|
||||||
|
"invitation.export.not_found",
|
||||||
|
`Invitation not found: ${invitationIdentifier}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const serializedInvitation = serializeInvitation(invitation.data);
|
||||||
|
|
||||||
|
const outputFile = options["output"] ?? args[1];
|
||||||
|
|
||||||
|
if (!outputFile) {
|
||||||
|
deps.io.out(serializedInvitation);
|
||||||
|
return { invitationIdentifier };
|
||||||
|
}
|
||||||
|
|
||||||
|
const outputPath = path.resolve(process.cwd(), outputFile);
|
||||||
|
try {
|
||||||
|
writeFileSync(outputPath, serializedInvitation);
|
||||||
|
} catch (error) {
|
||||||
|
throw new CommandError(
|
||||||
|
"invitation.export.write_failed",
|
||||||
|
`Failed to export invitation to file: ${outputPath} (${error instanceof Error ? error.message : "unknown error"})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
deps.io.out(`Invitation exported to: ${outputPath}`);
|
||||||
|
return { invitationIdentifier, outputFile: outputPath };
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles the invitation command.
|
* Handles the invitation command.
|
||||||
* Throws CommandError on failure, returns result data on success.
|
* Throws CommandError on failure, returns result data on success.
|
||||||
@@ -411,7 +484,7 @@ export const handleInvitationCommand = async (
|
|||||||
deps.io.verbose(`Invitation file path: ${invitationFilePath}`);
|
deps.io.verbose(`Invitation file path: ${invitationFilePath}`);
|
||||||
writeFileSync(
|
writeFileSync(
|
||||||
invitationFilePath,
|
invitationFilePath,
|
||||||
encodeExtendedJson(invitationInstance.data, 2),
|
formatInvitationForFile(invitationInstance.data),
|
||||||
);
|
);
|
||||||
deps.io.out(
|
deps.io.out(
|
||||||
`Invitation created: ${path.basename(invitationFilePath)} (${invitationInstance.data.invitationIdentifier})`,
|
`Invitation created: ${path.basename(invitationFilePath)} (${invitationInstance.data.invitationIdentifier})`,
|
||||||
@@ -421,11 +494,8 @@ export const handleInvitationCommand = async (
|
|||||||
const missingRequirements =
|
const missingRequirements =
|
||||||
await invitationInstance.getMissingRequirements();
|
await invitationInstance.getMissingRequirements();
|
||||||
const hasMissing =
|
const hasMissing =
|
||||||
(missingRequirements.variables?.length ?? 0) > 0 ||
|
hasMissingRequirements(missingRequirements.templateRequirements) ||
|
||||||
(missingRequirements.inputs?.length ?? 0) > 0 ||
|
missingRequirements.inputsMissingSignatures.length > 0;
|
||||||
(missingRequirements.outputs?.length ?? 0) > 0 ||
|
|
||||||
(missingRequirements.roles !== undefined &&
|
|
||||||
Object.keys(missingRequirements.roles).length > 0);
|
|
||||||
|
|
||||||
// If there are missing requirements, print them out
|
// If there are missing requirements, print them out
|
||||||
if (hasMissing) {
|
if (hasMissing) {
|
||||||
@@ -532,7 +602,10 @@ export const handleInvitationCommand = async (
|
|||||||
// Write the invitation to a file in the working directory
|
// Write the invitation to a file in the working directory
|
||||||
// TODO: Support the -o flag to specify the output path
|
// TODO: Support the -o flag to specify the output path
|
||||||
const invitationFilePath = `${deps.paths.workingDir}/inv-${invitation.data.invitationIdentifier}.json`;
|
const invitationFilePath = `${deps.paths.workingDir}/inv-${invitation.data.invitationIdentifier}.json`;
|
||||||
writeFileSync(invitationFilePath, encodeExtendedJson(invitation.data, 2));
|
writeFileSync(
|
||||||
|
invitationFilePath,
|
||||||
|
formatInvitationForFile(invitation.data),
|
||||||
|
);
|
||||||
deps.io.out(
|
deps.io.out(
|
||||||
`Invitation updated: ${path.basename(invitationFilePath)} (${invitation.data.invitationIdentifier})`,
|
`Invitation updated: ${path.basename(invitationFilePath)} (${invitation.data.invitationIdentifier})`,
|
||||||
);
|
);
|
||||||
@@ -540,11 +613,8 @@ export const handleInvitationCommand = async (
|
|||||||
// Get the missing requirements for the invitation. This will tell us if we are missing any variables, inputs, outputs, or roles.
|
// Get the missing requirements for the invitation. This will tell us if we are missing any variables, inputs, outputs, or roles.
|
||||||
const missingRequirements = await invitation.getMissingRequirements();
|
const missingRequirements = await invitation.getMissingRequirements();
|
||||||
const hasMissing =
|
const hasMissing =
|
||||||
(missingRequirements.variables?.length ?? 0) > 0 ||
|
hasMissingRequirements(missingRequirements.templateRequirements) ||
|
||||||
(missingRequirements.inputs?.length ?? 0) > 0 ||
|
missingRequirements.inputsMissingSignatures.length > 0;
|
||||||
(missingRequirements.outputs?.length ?? 0) > 0 ||
|
|
||||||
(missingRequirements.roles !== undefined &&
|
|
||||||
Object.keys(missingRequirements.roles).length > 0);
|
|
||||||
|
|
||||||
// If there are missing requirements, print them out
|
// If there are missing requirements, print them out
|
||||||
if (hasMissing) {
|
if (hasMissing) {
|
||||||
@@ -721,11 +791,10 @@ export const handleInvitationCommand = async (
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Read the invitation file (XOInvitation format, can be passed to the engine directly)
|
// Read the invitation file (XOInvitation format, can be passed to the engine directly)
|
||||||
const invitationFile = await readFileSync(invitationFilePath, "utf8");
|
const invitationFile = readFileSync(invitationFilePath, "utf8");
|
||||||
deps.io.verbose(`Invitation file: ${invitationFile}`);
|
deps.io.verbose(`Invitation file: ${invitationFile}`);
|
||||||
|
|
||||||
// Parse the invitation file
|
const invitation = deserializeInvitation(invitationFile);
|
||||||
const invitation = JSON.parse(invitationFile);
|
|
||||||
deps.io.verbose(`Invitation: ${formatObject(invitation)}`);
|
deps.io.verbose(`Invitation: ${formatObject(invitation)}`);
|
||||||
|
|
||||||
// Create the invitation instance (NOTE: Not an engine compatible invitation. This is the wrapped format)
|
// Create the invitation instance (NOTE: Not an engine compatible invitation. This is the wrapped format)
|
||||||
@@ -839,19 +908,27 @@ export const handleInvitationCommand = async (
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Read the invitation file (XOInvitation format, can be passed to the engine directly)
|
// Read the invitation file (XOInvitation format, can be passed to the engine directly)
|
||||||
const invitationFile = await readFileSync(invitationFilePath, "utf8");
|
const invitationFile = readFileSync(invitationFilePath, "utf8");
|
||||||
deps.io.verbose(`Invitation file: ${invitationFile}`);
|
deps.io.verbose(`Invitation file: ${invitationFile}`);
|
||||||
|
|
||||||
// Parse the invitation file
|
const invitation = deserializeInvitation(invitationFile);
|
||||||
const invitation = JSON.parse(invitationFile);
|
|
||||||
deps.io.verbose(`Invitation: ${formatObject(invitation)}`);
|
deps.io.verbose(`Invitation: ${formatObject(invitation)}`);
|
||||||
|
|
||||||
// "Creates" the invitiation in the engine. This method acts as both creation or import depending on the data that is being passed in
|
const template = await deps.app.engine.getTemplate(
|
||||||
const xoInvitation = await deps.app.engine.createInvitation(invitation);
|
invitation.templateIdentifier,
|
||||||
deps.io.verbose(`XOInvitation: ${formatObject(xoInvitation)}`);
|
);
|
||||||
|
if (!template) {
|
||||||
|
throw new CommandError(
|
||||||
|
"invitation.import.template_not_found",
|
||||||
|
`Template not found: ${invitation.templateIdentifier}. ` +
|
||||||
|
`Import the matching template first with: xo-cli template import <template-file>`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Create the invitation instance (NOTE: Not an engine compatible invitation. This is the wrapped format)
|
// Accept and track the invitation. Invitation.create calls acceptInvitation
|
||||||
const invitationInstance = await deps.app.createInvitation(xoInvitation);
|
// internally — do not call engine.createInvitation here, that creates a new
|
||||||
|
// invitation and discards the imported commits.
|
||||||
|
const invitationInstance = await deps.app.createInvitation(invitation);
|
||||||
deps.io.verbose(
|
deps.io.verbose(
|
||||||
`Invitation created: ${formatObject(invitationInstance.data)}`,
|
`Invitation created: ${formatObject(invitationInstance.data)}`,
|
||||||
);
|
);
|
||||||
@@ -862,6 +939,10 @@ export const handleInvitationCommand = async (
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case "export": {
|
||||||
|
return handleInvitationExportCommand(deps, args.slice(1), options);
|
||||||
|
}
|
||||||
|
|
||||||
case "list": {
|
case "list": {
|
||||||
// List all the invitations
|
// List all the invitations
|
||||||
const invitations = await Promise.all(
|
const invitations = await Promise.all(
|
||||||
|
|||||||
@@ -2,8 +2,14 @@ import { hexToBin } from "@bitauth/libauth";
|
|||||||
|
|
||||||
import { bold, dim } from "../utils.js";
|
import { bold, dim } from "../utils.js";
|
||||||
import type { CommandDependencies, CommandIO } from "./types.js";
|
import type { CommandDependencies, CommandIO } from "./types.js";
|
||||||
import type { UnspentOutputData } from "@xo-cash/state";
|
|
||||||
import { CommandError } from "./types.js";
|
import { CommandError } from "./types.js";
|
||||||
|
import type { XOTemplate } from "@xo-cash/types";
|
||||||
|
import { generateTemplateIdentifier } from "@xo-cash/engine";
|
||||||
|
import {
|
||||||
|
buildScriptHashDataMap,
|
||||||
|
enrichUnspentOutput,
|
||||||
|
type UnspentOutputWithMetadata,
|
||||||
|
} from "../../utils/utxo-metadata.js";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Prints the help message for the resource command.
|
* Prints the help message for the resource command.
|
||||||
@@ -27,9 +33,12 @@ ${bold("Sub-commands:")}
|
|||||||
* Formats a single UTXO for display, optionally including reservation info.
|
* Formats a single UTXO for display, optionally including reservation info.
|
||||||
*/
|
*/
|
||||||
function formatResource(
|
function formatResource(
|
||||||
resource: UnspentOutputData,
|
resource: UnspentOutputWithMetadata & { template?: XOTemplate },
|
||||||
showReserved = false,
|
showReserved = false,
|
||||||
): string {
|
): string {
|
||||||
|
// Format the template
|
||||||
|
const template = resource.template ? dim(`[${generateTemplateIdentifier(resource.template)}]`) : "";
|
||||||
|
|
||||||
// Format the outpoint
|
// Format the outpoint
|
||||||
const outpoint = bold(
|
const outpoint = bold(
|
||||||
`${resource.outpointTransactionHash}:${resource.outpointIndex}`,
|
`${resource.outpointTransactionHash}:${resource.outpointIndex}`,
|
||||||
@@ -39,7 +48,9 @@ function formatResource(
|
|||||||
const value = dim(`${resource.valueSatoshis} sats`);
|
const value = dim(`${resource.valueSatoshis} sats`);
|
||||||
|
|
||||||
// Format the output
|
// Format the output
|
||||||
const output = dim(resource.outputIdentifier);
|
const output = resource.outputIdentifier
|
||||||
|
? dim(resource.outputIdentifier)
|
||||||
|
: "";
|
||||||
|
|
||||||
// Format the height
|
// Format the height
|
||||||
const height = dim(`(height ${resource.minedAtHeight})`);
|
const height = dim(`(height ${resource.minedAtHeight})`);
|
||||||
@@ -47,11 +58,11 @@ function formatResource(
|
|||||||
// If the resource is reserved, format the reservation info
|
// If the resource is reserved, format the reservation info
|
||||||
if (showReserved && resource.reservedBy) {
|
if (showReserved && resource.reservedBy) {
|
||||||
const inv = dim(`reserved for ${resource.reservedBy}`);
|
const inv = dim(`reserved for ${resource.reservedBy}`);
|
||||||
return `${outpoint} ${value} ${output} ${height} ${inv}`;
|
return `${template} ${outpoint} ${value} ${output} ${height} ${inv}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Otherwise, format the resource without reservation info
|
// Otherwise, format the resource without reservation info
|
||||||
return `${outpoint} ${value} ${output} ${height}`;
|
return `${template} ${outpoint} ${value} ${output} ${height}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -108,9 +119,30 @@ export const handleResourceCommand = async (
|
|||||||
return { count: 0 };
|
return { count: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const scriptHashDataByScriptHash = await buildScriptHashDataMap(
|
||||||
|
deps.app.engine,
|
||||||
|
);
|
||||||
|
|
||||||
|
const resourcesWithTemplateInformation = await Promise.all(
|
||||||
|
filtered.map(async (resource) => {
|
||||||
|
const enriched = enrichUnspentOutput(
|
||||||
|
resource,
|
||||||
|
scriptHashDataByScriptHash,
|
||||||
|
);
|
||||||
|
const template = enriched.templateIdentifier
|
||||||
|
? await deps.app.engine.getTemplate(enriched.templateIdentifier)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
return {
|
||||||
|
...enriched,
|
||||||
|
template,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
// Format the resources into a list of strings that we can display to the user
|
// Format the resources into a list of strings that we can display to the user
|
||||||
const showReserved = qualifier === "all" || qualifier === "reserved";
|
const showReserved = qualifier === "all" || qualifier === "reserved";
|
||||||
const formattedResources = filtered.map((r) =>
|
const formattedResources = resourcesWithTemplateInformation.map((r) =>
|
||||||
formatResource(r, showReserved),
|
formatResource(r, showReserved),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { existsSync, readFileSync } from "fs";
|
import { existsSync, readFileSync, writeFileSync } from "fs";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
import { generateTemplateIdentifier } from "@xo-cash/engine";
|
import { generateTemplateIdentifier } from "@xo-cash/engine";
|
||||||
import type { XOTemplate } from "@xo-cash/types";
|
import type { XOTemplate } from "@xo-cash/types";
|
||||||
@@ -23,6 +23,10 @@ ${bold("Sub-commands:")}
|
|||||||
- list <category> <identifier> ${dim("List all options of the field type in a template")}
|
- list <category> <identifier> ${dim("List all options of the field type in a template")}
|
||||||
- inspect <category> <identifier> <field> ${dim("Inspect a field in a template")}
|
- inspect <category> <identifier> <field> ${dim("Inspect a field in a template")}
|
||||||
- set-default <template-file> <output-identifier> <role-identifier> ${dim("Set the default template")}
|
- set-default <template-file> <output-identifier> <role-identifier> ${dim("Set the default template")}
|
||||||
|
- export <template-identifier> [output-file] ${dim("Export a template to stdout or a file")}
|
||||||
|
|
||||||
|
${bold("Options:")}
|
||||||
|
-o --output <output-filename> ${dim("Output filename for the exported template")}
|
||||||
`,
|
`,
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -338,6 +342,71 @@ export const handleTemplateInspectCommand = async (
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles the template export command.
|
||||||
|
* Throws CommandError on failure, returns result data on success.
|
||||||
|
* @param deps - The command dependencies.
|
||||||
|
* @param args - Positional args after "export", e.g. ["template-id"] or ["template-id", "template.json"].
|
||||||
|
* @param options - Parsed option flags.
|
||||||
|
*/
|
||||||
|
export const handleTemplateExportCommand = async (
|
||||||
|
deps: CommandDependencies,
|
||||||
|
args: string[],
|
||||||
|
options: Record<string, string>,
|
||||||
|
): Promise<{ outputFile?: string }> => {
|
||||||
|
// Get the template identifier from the arguments
|
||||||
|
const templateIdentifier = args[0];
|
||||||
|
|
||||||
|
// If no template identifier is provided, print a message and throw an error
|
||||||
|
if (!templateIdentifier) {
|
||||||
|
deps.io.err("No template identifier provided");
|
||||||
|
printTemplateHelp(deps.io);
|
||||||
|
throw new CommandError(
|
||||||
|
"template.export.identifier_missing",
|
||||||
|
"No template identifier provided",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the raw template from the engine.
|
||||||
|
// Do not resolve references or pretty-print the template.
|
||||||
|
const rawTemplate = await deps.app.engine.getTemplate(templateIdentifier);
|
||||||
|
|
||||||
|
// If the raw template is not found, print a message and throw an error
|
||||||
|
if (!rawTemplate) {
|
||||||
|
deps.io.err(`No template found: ${templateIdentifier}`);
|
||||||
|
throw new CommandError(
|
||||||
|
"template.export.not_found",
|
||||||
|
`No template found: ${templateIdentifier}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serialize the template without indentation to preserve the engine output shape.
|
||||||
|
const serializedTemplate = JSON.stringify(rawTemplate);
|
||||||
|
|
||||||
|
// Resolve output file from --output (or -o), then fallback to optional positional output file
|
||||||
|
const outputFile = options["output"] ?? args[1];
|
||||||
|
|
||||||
|
// If no output file is provided, print the template to stdout
|
||||||
|
if (!outputFile) {
|
||||||
|
deps.io.out(serializedTemplate);
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve output file path and write the template to disk
|
||||||
|
const outputPath = path.resolve(process.cwd(), outputFile);
|
||||||
|
try {
|
||||||
|
writeFileSync(outputPath, serializedTemplate);
|
||||||
|
} catch (error) {
|
||||||
|
throw new CommandError(
|
||||||
|
"template.export.write_failed",
|
||||||
|
`Failed to export template to file: ${outputPath} (${error instanceof Error ? error.message : "unknown error"})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
deps.io.out(`Template exported to: ${outputPath}`);
|
||||||
|
return { outputFile: outputPath };
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles the template command.
|
* Handles the template command.
|
||||||
* Throws CommandError on failure, returns result data on success.
|
* Throws CommandError on failure, returns result data on success.
|
||||||
@@ -348,8 +417,8 @@ export const handleTemplateInspectCommand = async (
|
|||||||
export const handleTemplateCommand = async (
|
export const handleTemplateCommand = async (
|
||||||
deps: CommandDependencies,
|
deps: CommandDependencies,
|
||||||
args: string[],
|
args: string[],
|
||||||
_options: Record<string, string>,
|
options: Record<string, string>,
|
||||||
): Promise<{ templateFile?: string; count?: number }> => {
|
): Promise<{ templateFile?: string; count?: number; outputFile?: string }> => {
|
||||||
// Get the sub-command from the arguments
|
// Get the sub-command from the arguments
|
||||||
const subCommand = args[0];
|
const subCommand = args[0];
|
||||||
|
|
||||||
@@ -414,6 +483,10 @@ export const handleTemplateCommand = async (
|
|||||||
// Handle the template inspect command, We offload here as it has lots of arguments and is quite long
|
// Handle the template inspect command, We offload here as it has lots of arguments and is quite long
|
||||||
return handleTemplateInspectCommand(deps, args.slice(1));
|
return handleTemplateInspectCommand(deps, args.slice(1));
|
||||||
}
|
}
|
||||||
|
case "export": {
|
||||||
|
// Handle the template export command
|
||||||
|
return handleTemplateExportCommand(deps, args.slice(1), options);
|
||||||
|
}
|
||||||
case "set-default": {
|
case "set-default": {
|
||||||
// Get the template file, output identifier, and role identifier from the arguments
|
// Get the template file, output identifier, and role identifier from the arguments
|
||||||
const templateFile = args[1];
|
const templateFile = args[1];
|
||||||
|
|||||||
@@ -18,10 +18,13 @@ import { EventEmitter } from "../utils/event-emitter.js";
|
|||||||
|
|
||||||
// TODO: Remove this. Exists to hash the seed for database namespace.
|
// TODO: Remove this. Exists to hash the seed for database namespace.
|
||||||
import { createHash } from "crypto";
|
import { createHash } from "crypto";
|
||||||
import { p2pkhTemplate } from "@xo-cash/templates";
|
|
||||||
import { hexToBin } from "@bitauth/libauth";
|
import { hexToBin } from "@bitauth/libauth";
|
||||||
import { parseTemplate } from "@xo-cash/engine";
|
import { parseTemplate } from "@xo-cash/engine";
|
||||||
|
|
||||||
|
import { p2pkhTemplate } from "@xo-cash/templates";
|
||||||
|
import { vendingMachineTemplate } from "../templates/vending-machine.js";
|
||||||
|
import { wrapBCHTemplate } from "../templates/wrap-template.js";
|
||||||
|
|
||||||
export type AppEventMap = {
|
export type AppEventMap = {
|
||||||
"invitation-added": Invitation;
|
"invitation-added": Invitation;
|
||||||
"invitation-removed": Invitation;
|
"invitation-removed": Invitation;
|
||||||
@@ -53,6 +56,12 @@ export class AppService extends EventEmitter<AppEventMap> {
|
|||||||
public settings: SettingsService;
|
public settings: SettingsService;
|
||||||
|
|
||||||
public invitations: Invitation[] = [];
|
public invitations: Invitation[] = [];
|
||||||
|
/**
|
||||||
|
* Incremented whenever the invitation list or any invitation's data/status changes.
|
||||||
|
* Used by TUI hooks so useSyncExternalStore snapshots change on in-place mutations.
|
||||||
|
*/
|
||||||
|
public invitationsRevision = 0;
|
||||||
|
private invitationRevisions = new Map<string, number>();
|
||||||
private invitationEventCleanup = new Map<
|
private invitationEventCleanup = new Map<
|
||||||
string,
|
string,
|
||||||
{
|
{
|
||||||
@@ -81,22 +90,9 @@ export class AppService extends EventEmitter<AppEventMap> {
|
|||||||
|
|
||||||
// TODO: We *technically* dont want this here, but we also need some initial templates for the wallet, so im doing it here
|
// TODO: We *technically* dont want this here, but we also need some initial templates for the wallet, so im doing it here
|
||||||
// Import the default P2PKH template
|
// Import the default P2PKH template
|
||||||
const { templateIdentifier } = await engine.importTemplate(p2pkhTemplate);
|
await engine.importTemplate(p2pkhTemplate);
|
||||||
|
await engine.importTemplate(vendingMachineTemplate);
|
||||||
// engine
|
await engine.importTemplate(wrapBCHTemplate);
|
||||||
// .subscribeToLockingBytecodesForTemplate(templateIdentifier)
|
|
||||||
// .catch((err) =>
|
|
||||||
// console.error(
|
|
||||||
// `Error subscribing to locking bytecodes for template ${templateIdentifier}: ${err}`,
|
|
||||||
// ),
|
|
||||||
// );
|
|
||||||
// engine
|
|
||||||
// .updateUnspentOutputsForTemplate(templateIdentifier)
|
|
||||||
// .catch((err) =>
|
|
||||||
// console.error(
|
|
||||||
// `Error updating unspent outputs for template ${templateIdentifier}: ${err}`,
|
|
||||||
// ),
|
|
||||||
// );
|
|
||||||
|
|
||||||
// Update all the unspents for every template, and subscribe to the locking bytecodes for changes
|
// Update all the unspents for every template, and subscribe to the locking bytecodes for changes
|
||||||
// TODO: Remove the above lines that do the same thing. Minimising changes for BLISS.
|
// TODO: Remove the above lines that do the same thing. Minimising changes for BLISS.
|
||||||
@@ -104,8 +100,8 @@ export class AppService extends EventEmitter<AppEventMap> {
|
|||||||
const templates = await engine.listImportedTemplates();
|
const templates = await engine.listImportedTemplates();
|
||||||
|
|
||||||
templates.forEach(async (template) => {
|
templates.forEach(async (template) => {
|
||||||
// engine.updateUnspentOutputsForTemplate(generateTemplateIdentifier(template));
|
engine.updateUnspentOutputsForTemplate(generateTemplateIdentifier(template));
|
||||||
engine.subscribeToLockingBytecodesForTemplate(generateTemplateIdentifier(template));
|
engine.subscribeToScriptHashForTemplate(generateTemplateIdentifier(template));
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -175,8 +171,9 @@ export class AppService extends EventEmitter<AppEventMap> {
|
|||||||
// Create the invitation
|
// Create the invitation
|
||||||
const invitationInstance = await Invitation.create(invitation, deps);
|
const invitationInstance = await Invitation.create(invitation, deps);
|
||||||
|
|
||||||
// Add the invitation to the invitations array
|
// Attach listeners before SSE connects so updates are not missed.
|
||||||
await this.addInvitation(invitationInstance);
|
await this.addInvitation(invitationInstance);
|
||||||
|
await invitationInstance.start();
|
||||||
|
|
||||||
return invitationInstance;
|
return invitationInstance;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import { binToHex, hexToBin, sha256 } from "@bitauth/libauth";
|
import { binToHex, hexToBin, sha256 } from "@bitauth/libauth";
|
||||||
import { compileCashAssemblyString, type Engine } from "@xo-cash/engine";
|
import { compileCashAssemblyString, type Engine } from "@xo-cash/engine";
|
||||||
import type { ScriptHashData, UnspentOutputData } from "@xo-cash/state";
|
import type { ScriptHashData, State, UnspentOutputData } from "@xo-cash/state";
|
||||||
import type {
|
import type {
|
||||||
XOInvitation,
|
XOInvitation,
|
||||||
XOInvitationCommit,
|
|
||||||
XOInvitationInput,
|
XOInvitationInput,
|
||||||
XOInvitationOutput,
|
XOInvitationOutput,
|
||||||
XOInvitationVariableValue,
|
XOInvitationVariableValue,
|
||||||
@@ -146,8 +145,10 @@ export class HistoryService {
|
|||||||
const contexts = new Map<string, InvitationContext>();
|
const contexts = new Map<string, InvitationContext>();
|
||||||
|
|
||||||
for (const invitation of this.invitations) {
|
for (const invitation of this.invitations) {
|
||||||
const template =
|
const templateIdentifier = invitation.data.templateIdentifier;
|
||||||
(await this.engine.getTemplate(invitation.data.templateIdentifier)) ?? null;
|
const template = templateIdentifier
|
||||||
|
? (await this.engine.getTemplate(templateIdentifier)) ?? null
|
||||||
|
: null;
|
||||||
contexts.set(invitation.data.invitationIdentifier, {
|
contexts.set(invitation.data.invitationIdentifier, {
|
||||||
invitation,
|
invitation,
|
||||||
template,
|
template,
|
||||||
@@ -164,11 +165,19 @@ export class HistoryService {
|
|||||||
const scriptHashDataByScriptHash = new Map<string, ScriptHashData>();
|
const scriptHashDataByScriptHash = new Map<string, ScriptHashData>();
|
||||||
const templateIdentifiers = new Set<string>();
|
const templateIdentifiers = new Set<string>();
|
||||||
|
|
||||||
for (const utxo of allUtxos) {
|
|
||||||
templateIdentifiers.add(utxo.templateIdentifier);
|
|
||||||
}
|
|
||||||
for (const invitation of this.invitations) {
|
for (const invitation of this.invitations) {
|
||||||
templateIdentifiers.add(invitation.data.templateIdentifier);
|
if (invitation.data.templateIdentifier) {
|
||||||
|
templateIdentifiers.add(invitation.data.templateIdentifier);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const uniqueScriptHashes = new Set(allUtxos.map((utxo) => utxo.scriptHash));
|
||||||
|
for (const scriptHash of uniqueScriptHashes) {
|
||||||
|
const scriptHashData = await this.getScriptHashData(scriptHash);
|
||||||
|
if (scriptHashData === undefined) continue;
|
||||||
|
|
||||||
|
scriptHashDataByScriptHash.set(scriptHash, scriptHashData);
|
||||||
|
templateIdentifiers.add(scriptHashData.templateIdentifier);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const templateIdentifier of templateIdentifiers) {
|
for (const templateIdentifier of templateIdentifiers) {
|
||||||
@@ -186,8 +195,10 @@ export class HistoryService {
|
|||||||
metadataIndex: WalletMetadataIndex,
|
metadataIndex: WalletMetadataIndex,
|
||||||
): Promise<UtxoContext> {
|
): Promise<UtxoContext> {
|
||||||
const scriptHashData = metadataIndex.scriptHashDataByScriptHash.get(utxo.scriptHash);
|
const scriptHashData = metadataIndex.scriptHashDataByScriptHash.get(utxo.scriptHash);
|
||||||
const templateIdentifier = scriptHashData?.templateIdentifier ?? utxo.templateIdentifier;
|
const templateIdentifier = scriptHashData?.templateIdentifier;
|
||||||
const template = (await this.engine.getTemplate(templateIdentifier)) ?? null;
|
const template = templateIdentifier
|
||||||
|
? (await this.engine.getTemplate(templateIdentifier)) ?? null
|
||||||
|
: null;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
utxo,
|
utxo,
|
||||||
@@ -299,7 +310,7 @@ export class HistoryService {
|
|||||||
if (!matchingContext) continue;
|
if (!matchingContext) continue;
|
||||||
|
|
||||||
const lockingBytecode = this.getOutputLockingBytecodeHex(output) ?? matchingContext.scriptHashData?.lockingBytecode;
|
const lockingBytecode = this.getOutputLockingBytecodeHex(output) ?? matchingContext.scriptHashData?.lockingBytecode;
|
||||||
const outputIdentifier = output.outputIdentifier ?? matchingContext.scriptHashData?.outputIdentifier ?? matchingContext.utxo.outputIdentifier;
|
const outputIdentifier = output.outputIdentifier ?? matchingContext.scriptHashData?.outputIdentifier;
|
||||||
const role =
|
const role =
|
||||||
output.roleIdentifier ??
|
output.roleIdentifier ??
|
||||||
this.getFirstEntityRole(entityRoles, commit.entityIdentifier) ??
|
this.getFirstEntityRole(entityRoles, commit.entityIdentifier) ??
|
||||||
@@ -380,20 +391,21 @@ export class HistoryService {
|
|||||||
if (usedUtxoIds.has(this.getUtxoId(context.utxo))) return false;
|
if (usedUtxoIds.has(this.getUtxoId(context.utxo))) return false;
|
||||||
if (scriptHash && context.utxo.scriptHash === scriptHash) return true;
|
if (scriptHash && context.utxo.scriptHash === scriptHash) return true;
|
||||||
if (lockingBytecode && context.scriptHashData?.lockingBytecode === lockingBytecode) return true;
|
if (lockingBytecode && context.scriptHashData?.lockingBytecode === lockingBytecode) return true;
|
||||||
if (output.outputIdentifier && context.utxo.outputIdentifier === output.outputIdentifier) return true;
|
|
||||||
|
if (output.outputIdentifier && context.scriptHashData?.outputIdentifier === output.outputIdentifier) return true;
|
||||||
return false;
|
return false;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private projectStandaloneUtxo(context: UtxoContext): WalletHistoryItem {
|
private projectStandaloneUtxo(context: UtxoContext): WalletHistoryItem {
|
||||||
const output = this.projectUtxoOutput(context);
|
const output = this.projectUtxoOutput(context);
|
||||||
const templateIdentifier = context.scriptHashData?.templateIdentifier ?? context.utxo.templateIdentifier;
|
const templateIdentifier = context.scriptHashData?.templateIdentifier;
|
||||||
const role = output.role;
|
const role = output.role;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: `utxo-${context.utxo.outpointTransactionHash}:${context.utxo.outpointIndex}`,
|
id: `utxo-${context.utxo.outpointTransactionHash}:${context.utxo.outpointIndex}`,
|
||||||
source: "utxo",
|
source: "utxo",
|
||||||
templateIdentifier,
|
templateIdentifier: templateIdentifier ?? "",
|
||||||
template: context.template?.name ?? "UnknownTemplate",
|
template: context.template?.name ?? "UnknownTemplate",
|
||||||
roles: role ? [role] : ["unknown"],
|
roles: role ? [role] : ["unknown"],
|
||||||
description: output.description,
|
description: output.description,
|
||||||
@@ -404,7 +416,7 @@ export class HistoryService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private projectUtxoOutput(context: UtxoContext): WalletHistoryOutput {
|
private projectUtxoOutput(context: UtxoContext): WalletHistoryOutput {
|
||||||
const outputIdentifier = context.scriptHashData?.outputIdentifier ?? context.utxo.outputIdentifier;
|
const outputIdentifier = context.scriptHashData?.outputIdentifier;
|
||||||
const role = context.scriptHashData?.roleIdentifier;
|
const role = context.scriptHashData?.roleIdentifier;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -557,7 +569,7 @@ export class HistoryService {
|
|||||||
variables: Record<string, XOInvitationVariableValue>,
|
variables: Record<string, XOInvitationVariableValue>,
|
||||||
): string {
|
): string {
|
||||||
try {
|
try {
|
||||||
return compileCashAssemblyString(description, variables);
|
return compileCashAssemblyString({ cashAssemblyText: description, variables, evaluationDecodeMode: 'utf8' });
|
||||||
} catch {
|
} catch {
|
||||||
return this.interpolateSimpleCashAssemblyVariables(description, variables);
|
return this.interpolateSimpleCashAssemblyVariables(description, variables);
|
||||||
}
|
}
|
||||||
@@ -591,6 +603,10 @@ export class HistoryService {
|
|||||||
: binToHex(output.lockingBytecode);
|
: binToHex(output.lockingBytecode);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async getScriptHashData(scriptHash: string): Promise<ScriptHashData | undefined> {
|
||||||
|
return (this.engine as unknown as { state: State }).state.getScriptHashData(scriptHash);
|
||||||
|
}
|
||||||
|
|
||||||
private getOutpointKey(txid: string, index: number): string {
|
private getOutpointKey(txid: string, index: number): string {
|
||||||
return `${txid}:${index}`;
|
return `${txid}:${index}`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
import type {
|
import type {
|
||||||
AcceptInvitationParameters,
|
InvitationParameters,
|
||||||
AppendInvitationParameters,
|
|
||||||
Engine,
|
Engine,
|
||||||
GetSpendableResourcesParameters,
|
GetSpendableResourcesParameters,
|
||||||
} from "@xo-cash/engine";
|
} from "@xo-cash/engine";
|
||||||
import { generateTemplateIdentifier, hasInvitationExpired, mergeInvitationCommits } from "@xo-cash/engine";
|
import { generateTemplateIdentifier, hasInvitationExpired, mergeInvitationCommits, serializeInvitation } from "@xo-cash/engine";
|
||||||
import type {
|
import type {
|
||||||
XOInvitation,
|
XOInvitation,
|
||||||
XOInvitationCommit,
|
XOInvitationCommit,
|
||||||
@@ -86,13 +85,13 @@ export class Invitation extends EventEmitter<InvitationEventMap> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// engine invitation (I have no idea if this is required)
|
// engine invitation (I have no idea if this is required)
|
||||||
const engineInvitation = await dependencies.engine.acceptInvitation(invitation);
|
const engineInvitation = await dependencies.engine.importInvitation(serializeInvitation(invitation));
|
||||||
|
|
||||||
// Create the invitation
|
// Create the invitation
|
||||||
const invitationInstance = new Invitation(engineInvitation, dependencies);
|
const invitationInstance = new Invitation(engineInvitation, dependencies);
|
||||||
|
|
||||||
// Start the invitation and its tracking
|
// Start the invitation and its tracking
|
||||||
await invitationInstance.start();
|
invitationInstance.start();
|
||||||
|
|
||||||
return invitationInstance;
|
return invitationInstance;
|
||||||
}
|
}
|
||||||
@@ -150,6 +149,10 @@ export class Invitation extends EventEmitter<InvitationEventMap> {
|
|||||||
* Start the invitation - Connect sync server and download latest invitation data.
|
* Start the invitation - Connect sync server and download latest invitation data.
|
||||||
*/
|
*/
|
||||||
async start(): Promise<void> {
|
async start(): Promise<void> {
|
||||||
|
// Persist immediately so imports survive sync-server outages and appear in the TUI
|
||||||
|
// after a CLI import or app restart.
|
||||||
|
await this.storage.set(this.data.invitationIdentifier, this.data);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Connect to the sync server and get the invitation (in parallel)
|
// Connect to the sync server and get the invitation (in parallel)
|
||||||
const [_, invitation] = await Promise.all([
|
const [_, invitation] = await Promise.all([
|
||||||
@@ -279,7 +282,8 @@ export class Invitation extends EventEmitter<InvitationEventMap> {
|
|||||||
private async computeStatusInternal(): Promise<string> {
|
private async computeStatusInternal(): Promise<string> {
|
||||||
let missingReqs;
|
let missingReqs;
|
||||||
try {
|
try {
|
||||||
missingReqs = await this.engine.listMissingRequirements(this.data);
|
const missingRequirements = await this.engine.listMissingRequirements(this.data.invitationIdentifier);
|
||||||
|
missingReqs = missingRequirements.templateRequirements;
|
||||||
} catch {
|
} catch {
|
||||||
return "unknown";
|
return "unknown";
|
||||||
}
|
}
|
||||||
@@ -378,7 +382,7 @@ export class Invitation extends EventEmitter<InvitationEventMap> {
|
|||||||
/**
|
/**
|
||||||
* Accept the invitation
|
* Accept the invitation
|
||||||
*/
|
*/
|
||||||
async accept(acceptParams?: AcceptInvitationParameters): Promise<void> {
|
async accept(acceptParams?: InvitationParameters): Promise<void> {
|
||||||
// Accept the invitation
|
// Accept the invitation
|
||||||
this.data = await this.engine.acceptInvitation(this.data, acceptParams);
|
this.data = await this.engine.acceptInvitation(this.data, acceptParams);
|
||||||
|
|
||||||
@@ -394,7 +398,7 @@ export class Invitation extends EventEmitter<InvitationEventMap> {
|
|||||||
*/
|
*/
|
||||||
async sign(): Promise<void> {
|
async sign(): Promise<void> {
|
||||||
// Sign the invitation
|
// Sign the invitation
|
||||||
const signedInvitation = await this.engine.signInvitation(this.data);
|
const signedInvitation = await this.engine.signInvitation(this.data.invitationIdentifier);
|
||||||
|
|
||||||
// Publish the signed invitation to the sync server
|
// Publish the signed invitation to the sync server
|
||||||
this.publishInvitation(signedInvitation);
|
this.publishInvitation(signedInvitation);
|
||||||
@@ -413,7 +417,7 @@ export class Invitation extends EventEmitter<InvitationEventMap> {
|
|||||||
* @returns The transaction hash returned by the network after broadcast.
|
* @returns The transaction hash returned by the network after broadcast.
|
||||||
*/
|
*/
|
||||||
async broadcast(): Promise<string> {
|
async broadcast(): Promise<string> {
|
||||||
const txHash = await this.engine.executeAction(this.data, {
|
const txHash = await this.engine.executeAction(this.data.invitationIdentifier, {
|
||||||
broadcastTransaction: true,
|
broadcastTransaction: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -429,9 +433,15 @@ export class Invitation extends EventEmitter<InvitationEventMap> {
|
|||||||
/**
|
/**
|
||||||
* Append a commit to the invitation
|
* Append a commit to the invitation
|
||||||
*/
|
*/
|
||||||
async append(data: AppendInvitationParameters): Promise<void> {
|
async append(data: InvitationParameters): Promise<void> {
|
||||||
|
try {
|
||||||
|
await this.engine.acceptInvitation(this.data);
|
||||||
|
} catch (err) {
|
||||||
|
// Literally do nothing here. We are just trying to accept the invitation in case we haven't already
|
||||||
|
}
|
||||||
|
|
||||||
// Append the commit to the invitation
|
// Append the commit to the invitation
|
||||||
this.data = await this.engine.appendInvitation(this.data, data);
|
this.data = await this.engine.appendInvitation(this.data.invitationIdentifier, data);
|
||||||
|
|
||||||
// Sync the invitation to the sync server
|
// Sync the invitation to the sync server
|
||||||
await this.publishInvitation(this.data);
|
await this.publishInvitation(this.data);
|
||||||
@@ -546,7 +556,7 @@ export class Invitation extends EventEmitter<InvitationEventMap> {
|
|||||||
* Get the missing requirements for the invitation
|
* Get the missing requirements for the invitation
|
||||||
*/
|
*/
|
||||||
async getMissingRequirements() {
|
async getMissingRequirements() {
|
||||||
return this.engine.listMissingRequirements(this.data);
|
return this.engine.listMissingRequirements(this.data.invitationIdentifier);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -608,33 +618,41 @@ export class Invitation extends EventEmitter<InvitationEventMap> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const valueSatoshisIdentifier = output.valueSatoshis;
|
const valueSatoshisExpression = output.valueSatoshis;
|
||||||
if (!valueSatoshisIdentifier) {
|
if (!valueSatoshisExpression) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Value satoshis identifier not found: ${outputIdentifier} in template: ${this.data.templateIdentifier}`,
|
`Value satoshis identifier not found: ${outputIdentifier} in template: ${this.data.templateIdentifier}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.dir(this.data, { depth: null });
|
||||||
|
|
||||||
// Create a list of all the variables from the commits
|
// Create a list of all the variables from the commits
|
||||||
const variables = this.data.commits.flatMap(
|
const variables = this.data.commits.flatMap(
|
||||||
(c) => c.data?.variables ?? [],
|
(c) => c.data?.variables ?? [],
|
||||||
);
|
);
|
||||||
|
console.dir(variables, { depth: null });
|
||||||
|
|
||||||
// Create a dictionary of the variables
|
// Create a dictionary of the variables
|
||||||
const formattedVariables = variables.reduce(
|
const formattedVariables = variables.reduce(
|
||||||
(acc, v) => {
|
(acc, v) => {
|
||||||
acc[v.variableIdentifier ?? ""] = v.value;
|
const { variableIdentifier, value } = v;
|
||||||
|
console.log(typeof value);
|
||||||
|
acc[variableIdentifier ?? ""] = value;
|
||||||
return acc;
|
return acc;
|
||||||
},
|
},
|
||||||
{} as Record<string, XOInvitationVariableValue>,
|
{} as Record<string, XOInvitationVariableValue>,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
console.dir(formattedVariables, { depth: null });
|
||||||
|
|
||||||
// Compile the CashAssembly expression to get the value satoshis (It handles the variable replacement for us)
|
// Compile the CashAssembly expression to get the value satoshis (It handles the variable replacement for us)
|
||||||
const valueSatoshis = await compileCashAssemblyString(
|
const valueSatoshis = compileCashAssemblyString(
|
||||||
String(valueSatoshisIdentifier),
|
{ cashAssemblyText: String(valueSatoshisExpression), variables: formattedVariables, evaluationDecodeMode: 'bigint' },
|
||||||
formattedVariables,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
console.dir(valueSatoshis, { depth: null });
|
||||||
|
|
||||||
// Return the value satoshis as a bigint
|
// Return the value satoshis as a bigint
|
||||||
// TODO: Check this of a vulnerability or crash - I assume there might be one if someone made the `valueSatoshis` a malicious expression
|
// TODO: Check this of a vulnerability or crash - I assume there might be one if someone made the `valueSatoshis` a malicious expression
|
||||||
return BigInt(valueSatoshis);
|
return BigInt(valueSatoshis);
|
||||||
@@ -688,9 +706,13 @@ export class Invitation extends EventEmitter<InvitationEventMap> {
|
|||||||
// Iterate through the outputs and sum the valueSatoshis
|
// Iterate through the outputs and sum the valueSatoshis
|
||||||
for (const output of outputs) {
|
for (const output of outputs) {
|
||||||
if (typeof output === "string") {
|
if (typeof output === "string") {
|
||||||
totalSats += await this.getSatsOut(output);
|
const sats = await this.getSatsOut(output);
|
||||||
|
console.log(`Sats for output: ${output} is ${sats}`);
|
||||||
|
totalSats += sats
|
||||||
} else {
|
} else {
|
||||||
totalSats += await this.getSatsOut(output.output);
|
const sats = await this.getSatsOut(output.output);
|
||||||
|
console.log(`Sats for output: ${output.output} is ${sats}`);
|
||||||
|
totalSats += sats;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { OracleClient } from '@generalprotocols/oracle-client';
|
||||||
import { EventEmitter } from '../utils/event-emitter.js';
|
import { EventEmitter } from '../utils/event-emitter.js';
|
||||||
import {
|
import {
|
||||||
type RatesEventMap,
|
type RatesEventMap,
|
||||||
@@ -73,8 +74,17 @@ export class RatesService extends EventEmitter<RatesServiceEventMap> {
|
|||||||
settings: SettingsService,
|
settings: SettingsService,
|
||||||
adapter?: RatesAdapter,
|
adapter?: RatesAdapter,
|
||||||
): Promise<RatesService> {
|
): Promise<RatesService> {
|
||||||
const resolvedAdapter = adapter ?? (await RatesOracle.from(undefined, settings));
|
if (adapter) {
|
||||||
return new RatesService(resolvedAdapter, settings);
|
return new RatesService(adapter, settings);
|
||||||
|
}
|
||||||
|
|
||||||
|
const oracleClient = new OracleClient();
|
||||||
|
oracleClient.start();
|
||||||
|
|
||||||
|
const ratesOracle = new RatesOracle(oracleClient, settings);
|
||||||
|
ratesOracle.start();
|
||||||
|
|
||||||
|
return new RatesService(ratesOracle, settings);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import Database from "better-sqlite3";
|
import Database from "better-sqlite3";
|
||||||
import { decodeExtendedJson, encodeExtendedJson } from "../utils/ext-json.js";
|
import { deserializeInvitation, serializeInvitation } from "@xo-cash/engine";
|
||||||
|
import type { XOInvitation } from "@xo-cash/types";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This is not an actual storage adapter that we want to make use of. This storage adapter is a stop-gap while the engine is under development.
|
* This is not an actual storage adapter that we want to make use of. This storage adapter is a stop-gap while the engine is under development.
|
||||||
@@ -56,9 +57,8 @@ export class Storage extends BaseStorage {
|
|||||||
return fullKey.startsWith(prefix) ? fullKey.slice(prefix.length) : fullKey;
|
return fullKey.startsWith(prefix) ? fullKey.slice(prefix.length) : fullKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
async set(key: string, value: any): Promise<void> {
|
async set(key: string, value: XOInvitation): Promise<void> {
|
||||||
// Encode the extended json object
|
const encodedValue = serializeInvitation(value);
|
||||||
const encodedValue = encodeExtendedJson(value);
|
|
||||||
|
|
||||||
// Insert or replace the value into the database with full key (including basePath)
|
// Insert or replace the value into the database with full key (including basePath)
|
||||||
const fullKey = this.getFullKey(key);
|
const fullKey = this.getFullKey(key);
|
||||||
@@ -93,10 +93,10 @@ export class Storage extends BaseStorage {
|
|||||||
return !strippedKey.includes(".");
|
return !strippedKey.includes(".");
|
||||||
});
|
});
|
||||||
|
|
||||||
// Decode the extended json objects and strip basePath from keys
|
// Deserialize invitations and strip basePath from keys
|
||||||
return filteredRows.map((row) => ({
|
return filteredRows.map((row) => ({
|
||||||
key: this.stripBasePath(row.key),
|
key: this.stripBasePath(row.key),
|
||||||
value: decodeExtendedJson(row.value),
|
value: deserializeInvitation(row.value),
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,7 +111,7 @@ export class Storage extends BaseStorage {
|
|||||||
if (!row) return null;
|
if (!row) return null;
|
||||||
|
|
||||||
// Decode the extended json object
|
// Decode the extended json object
|
||||||
return decodeExtendedJson(row.value);
|
return deserializeInvitation(row.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
async remove(key: string): Promise<void> {
|
async remove(key: string): Promise<void> {
|
||||||
@@ -174,9 +174,9 @@ export class InMemoryStorage extends BaseStorage {
|
|||||||
return fullKey.startsWith(prefix) ? fullKey.slice(prefix.length) : fullKey;
|
return fullKey.startsWith(prefix) ? fullKey.slice(prefix.length) : fullKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
async set(key: string, value: any): Promise<void> {
|
async set(key: string, value: XOInvitation): Promise<void> {
|
||||||
const fullKey = this.getFullKey(key);
|
const fullKey = this.getFullKey(key);
|
||||||
const encodedValue = encodeExtendedJson(value);
|
const encodedValue = serializeInvitation(value);
|
||||||
this.store.set(fullKey, encodedValue);
|
this.store.set(fullKey, encodedValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -199,7 +199,7 @@ export class InMemoryStorage extends BaseStorage {
|
|||||||
|
|
||||||
return filteredRows.map((row) => ({
|
return filteredRows.map((row) => ({
|
||||||
key: this.stripBasePath(row.key),
|
key: this.stripBasePath(row.key),
|
||||||
value: decodeExtendedJson(row.value),
|
value: deserializeInvitation(row.value),
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,7 +208,7 @@ export class InMemoryStorage extends BaseStorage {
|
|||||||
const encodedValue = this.store.get(fullKey);
|
const encodedValue = this.store.get(fullKey);
|
||||||
if (encodedValue === undefined) return null;
|
if (encodedValue === undefined) return null;
|
||||||
|
|
||||||
return decodeExtendedJson(encodedValue);
|
return deserializeInvitation(encodedValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
async remove(key: string): Promise<void> {
|
async remove(key: string): Promise<void> {
|
||||||
|
|||||||
277
src/templates/vending-machine.ts
Normal file
277
src/templates/vending-machine.ts
Normal file
@@ -0,0 +1,277 @@
|
|||||||
|
import type { XOTemplate } from '@xo-cash/types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Vending machine payment template.
|
||||||
|
*
|
||||||
|
* Merchant creates a purchaseItems invitation with receipt variables;
|
||||||
|
* customer funds and signs the composable transaction.
|
||||||
|
*/
|
||||||
|
export const vendingMachineTemplate: XOTemplate = {
|
||||||
|
$schema: 'https://libauth.org/schemas/wallet-template-v0.schema.json',
|
||||||
|
name: 'Vending Machine',
|
||||||
|
description: 'Purchase items from a vending machine with an itemized receipt.',
|
||||||
|
icon: 'wallet',
|
||||||
|
version: '1',
|
||||||
|
supported: ['BCH_2023_05', 'BCH_2024_05', 'BCH_2025_05', 'BCH_2026_05'],
|
||||||
|
|
||||||
|
defaults: {
|
||||||
|
change: {
|
||||||
|
output: 'changeOutput',
|
||||||
|
role: 'merchant',
|
||||||
|
generate: ['merchantKey'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
roles: {
|
||||||
|
merchant: {
|
||||||
|
name: 'Merchant',
|
||||||
|
description: 'The vending machine operator receiving payment.',
|
||||||
|
icon: 'owner',
|
||||||
|
},
|
||||||
|
customer: {
|
||||||
|
name: 'Customer',
|
||||||
|
description: 'The customer paying for items.',
|
||||||
|
icon: 'sender',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
start: [
|
||||||
|
{
|
||||||
|
action: 'purchaseItems',
|
||||||
|
role: 'merchant',
|
||||||
|
generate: ['merchantKey'],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
|
||||||
|
actions: {
|
||||||
|
purchaseItems: {
|
||||||
|
name: 'Purchase Items',
|
||||||
|
description: 'Purchase: $(<receiptSummary>) for $(<totalSatoshis>) sats',
|
||||||
|
icon: 'request',
|
||||||
|
|
||||||
|
roles: {
|
||||||
|
merchant: {
|
||||||
|
name: 'Sell Items',
|
||||||
|
description: 'Receive payment for $(<receiptSummary>)',
|
||||||
|
icon: 'request',
|
||||||
|
requirements: {
|
||||||
|
secrets: ['merchantKey'],
|
||||||
|
variables: [
|
||||||
|
'totalSatoshis',
|
||||||
|
'orderId',
|
||||||
|
'merchantName',
|
||||||
|
'receiptSummary',
|
||||||
|
'lineItemsJson',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
customer: {
|
||||||
|
name: 'Pay',
|
||||||
|
description: 'Pay $(<totalSatoshis>) sats for $(<receiptSummary>)',
|
||||||
|
icon: 'send',
|
||||||
|
requirements: {},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
requirements: {
|
||||||
|
participants: [
|
||||||
|
{ role: 'merchant', slots: { min: 1, max: 1 } },
|
||||||
|
{ role: 'customer', slots: { min: 1 } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
|
||||||
|
transaction: 'purchaseItemsTransaction',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
transactions: {
|
||||||
|
purchaseItemsTransaction: {
|
||||||
|
name: 'Vending Purchase',
|
||||||
|
description: 'Order $(<orderId>): $(<receiptSummary>)',
|
||||||
|
icon: 'request',
|
||||||
|
|
||||||
|
roles: {
|
||||||
|
merchant: {
|
||||||
|
name: 'Received Payment',
|
||||||
|
description: 'Received $(<totalSatoshis>) sats from $(<merchantName>) sale',
|
||||||
|
icon: 'receive',
|
||||||
|
},
|
||||||
|
customer: {
|
||||||
|
name: 'Sent Payment',
|
||||||
|
description: 'Paid $(<totalSatoshis>) sats for $(<receiptSummary>)',
|
||||||
|
icon: 'send',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
inputs: [],
|
||||||
|
outputs: [{ output: 'purchaseOutput' }],
|
||||||
|
version: 2,
|
||||||
|
locktime: 0,
|
||||||
|
composable: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
/** No custom input templates — customer UTXOs are selected at funding time. */
|
||||||
|
inputs: {},
|
||||||
|
|
||||||
|
outputs: {
|
||||||
|
changeOutput: {
|
||||||
|
name: 'Change',
|
||||||
|
description: 'Funds returned as change.',
|
||||||
|
icon: 'receive',
|
||||||
|
lockingScript: 'merchantReceivingLockingScript',
|
||||||
|
},
|
||||||
|
purchaseOutput: {
|
||||||
|
name: 'Purchase Payment',
|
||||||
|
description: '$(<totalSatoshis>) sats to $(<merchantName>)',
|
||||||
|
icon: 'request',
|
||||||
|
|
||||||
|
roles: {
|
||||||
|
merchant: {
|
||||||
|
name: 'Payment Received',
|
||||||
|
description: 'Received $(<totalSatoshis>) sats for $(<receiptSummary>)',
|
||||||
|
},
|
||||||
|
customer: {
|
||||||
|
name: 'Payment Sent',
|
||||||
|
description: 'Sent $(<totalSatoshis>) sats for $(<receiptSummary>)',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
lockingScript: 'merchantReceivingLockingScript',
|
||||||
|
valueSatoshis: '$(<totalSatoshis>)',
|
||||||
|
token: null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
lockingScripts: {
|
||||||
|
merchantReceivingLockingScript: {
|
||||||
|
name: 'Merchant Receive',
|
||||||
|
description: 'Funds received by the vending machine merchant.',
|
||||||
|
icon: 'address',
|
||||||
|
lockingType: 'p2pkh',
|
||||||
|
lockingBytecode: 'lockMerchantP2PKH',
|
||||||
|
unlockingBytecode: 'unlockMerchantP2PKH',
|
||||||
|
actions: [],
|
||||||
|
state: { variables: [], secrets: [] },
|
||||||
|
balance: {},
|
||||||
|
roles: {
|
||||||
|
merchant: {
|
||||||
|
state: {
|
||||||
|
variables: [],
|
||||||
|
secrets: ['merchantKey'],
|
||||||
|
},
|
||||||
|
actions: [],
|
||||||
|
balance: {
|
||||||
|
satoshis: true,
|
||||||
|
fungibleTokens: true,
|
||||||
|
nonfungibleTokens: true,
|
||||||
|
},
|
||||||
|
selectable: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
scripts: {
|
||||||
|
lockMerchantP2PKH:
|
||||||
|
'OP_DUP OP_HASH160 <$(<merchantKey.public_key> OP_HASH160)> OP_EQUALVERIFY OP_CHECKSIG',
|
||||||
|
unlockMerchantP2PKH:
|
||||||
|
'<merchantKey.schnorr_signature.all_outputs> <merchantKey.public_key>',
|
||||||
|
},
|
||||||
|
|
||||||
|
constants: {
|
||||||
|
dustLimit: {
|
||||||
|
name: 'Dust Limit',
|
||||||
|
description: 'Minimum satoshis for P2PKH outputs.',
|
||||||
|
type: 'integer',
|
||||||
|
value: 546,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
variables: {
|
||||||
|
merchantKey: {
|
||||||
|
name: 'Merchant Private Key',
|
||||||
|
description: 'Private key for the vending machine merchant wallet.',
|
||||||
|
type: 'bytes',
|
||||||
|
hint: 'private_key',
|
||||||
|
},
|
||||||
|
totalSatoshis: {
|
||||||
|
name: 'Total Price',
|
||||||
|
description: 'Total purchase price in satoshis',
|
||||||
|
type: 'integer',
|
||||||
|
hint: 'satoshis',
|
||||||
|
},
|
||||||
|
orderId: {
|
||||||
|
name: 'Order ID',
|
||||||
|
description: 'Unique order identifier',
|
||||||
|
type: 'string',
|
||||||
|
},
|
||||||
|
merchantName: {
|
||||||
|
name: 'Merchant Name',
|
||||||
|
description: 'Display name of the vending machine',
|
||||||
|
type: 'string',
|
||||||
|
},
|
||||||
|
receiptSummary: {
|
||||||
|
name: 'Receipt Summary',
|
||||||
|
description: 'Human-readable list of purchased items',
|
||||||
|
type: 'string',
|
||||||
|
},
|
||||||
|
lineItemsJson: {
|
||||||
|
name: 'Line Items',
|
||||||
|
description: 'JSON-encoded line items for the purchase',
|
||||||
|
type: 'string',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
icons: [
|
||||||
|
{ name: 'wallet', hash: '0000000000000000000000' },
|
||||||
|
{ name: 'owner', hash: '0000000000000000000000' },
|
||||||
|
{ name: 'sender', hash: '0000000000000000000000' },
|
||||||
|
{ name: 'request', hash: '0000000000000000000000' },
|
||||||
|
{ name: 'receive', hash: '0000000000000000000000' },
|
||||||
|
{ name: 'send', hash: '0000000000000000000000' },
|
||||||
|
],
|
||||||
|
|
||||||
|
scenarios: [
|
||||||
|
{
|
||||||
|
name: 'purchase items happy path',
|
||||||
|
description: 'Merchant requests payment for vending machine items.',
|
||||||
|
action: 'purchaseItems',
|
||||||
|
roles: [
|
||||||
|
{
|
||||||
|
role: 'merchant',
|
||||||
|
values: {
|
||||||
|
generated: {
|
||||||
|
merchantKey: 'KyRQa5pEXuzVcDwnXRLpYAascjchQW5DoxVRMbj4DTxS83573mz8',
|
||||||
|
},
|
||||||
|
variables: {
|
||||||
|
totalSatoshis: 3500,
|
||||||
|
orderId: 'order-demo-1',
|
||||||
|
merchantName: 'XO Snack Machine',
|
||||||
|
receiptSummary: '2× Cola, 1× Chips',
|
||||||
|
lineItemsJson: '[{"name":"Cola","qty":2},{"name":"Chips","qty":1}]',
|
||||||
|
},
|
||||||
|
secrets: {},
|
||||||
|
inputs: [],
|
||||||
|
outputs: [
|
||||||
|
{
|
||||||
|
lockingBytecode: '76a91475c715ecb74178fe87933e57e947e5e92d904b8188ac',
|
||||||
|
valueSatoshis: 3500,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
role: 'customer',
|
||||||
|
values: {
|
||||||
|
generated: {},
|
||||||
|
variables: {},
|
||||||
|
secrets: {},
|
||||||
|
inputs: [],
|
||||||
|
outputs: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
@@ -71,7 +71,7 @@ export function AppProvider({
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Start the AppService (loads existing invitations)
|
// Start the AppService (loads existing invitations)
|
||||||
await service.start();
|
service.start();
|
||||||
|
|
||||||
// Set the service and mark as initialized
|
// Set the service and mark as initialized
|
||||||
setAppService(service);
|
setAppService(service);
|
||||||
|
|||||||
@@ -158,9 +158,7 @@ export function SeedInputScreen(): React.ReactElement {
|
|||||||
setSeedPhrase('');
|
setSeedPhrase('');
|
||||||
setSaveMnemonicChecked(false);
|
setSaveMnemonicChecked(false);
|
||||||
|
|
||||||
setTimeout(() => {
|
navigate('wallet');
|
||||||
navigate('wallet');
|
|
||||||
}, 500);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message =
|
const message =
|
||||||
error instanceof Error ? error.message : 'Failed to initialize wallet';
|
error instanceof Error ? error.message : 'Failed to initialize wallet';
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import {
|
|||||||
formatActionListItem,
|
formatActionListItem,
|
||||||
getTemplateRoles,
|
getTemplateRoles,
|
||||||
} from '../../utils/template-utils.js';
|
} from '../../utils/template-utils.js';
|
||||||
|
import { buildScriptHashDataMap } from '../../utils/utxo-metadata.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Template item with metadata.
|
* Template item with metadata.
|
||||||
@@ -83,12 +84,21 @@ export function TemplateListScreen(): React.ReactElement {
|
|||||||
|
|
||||||
const templateList = await appService.engine.listImportedTemplates();
|
const templateList = await appService.engine.listImportedTemplates();
|
||||||
const allUtxos = await appService.engine.listUnspentOutputsData();
|
const allUtxos = await appService.engine.listUnspentOutputsData();
|
||||||
|
const scriptHashDataByScriptHash =
|
||||||
|
await buildScriptHashDataMap(appService.engine);
|
||||||
|
|
||||||
const ownedOutputsByTemplate = new Map<string, Set<string>>();
|
const ownedOutputsByTemplate = new Map<string, Set<string>>();
|
||||||
for (const utxo of allUtxos) {
|
for (const utxo of allUtxos) {
|
||||||
const existing = ownedOutputsByTemplate.get(utxo.templateIdentifier) ?? new Set<string>();
|
const scriptRow = scriptHashDataByScriptHash.get(utxo.scriptHash);
|
||||||
existing.add(utxo.outputIdentifier);
|
if (scriptRow === undefined) {
|
||||||
ownedOutputsByTemplate.set(utxo.templateIdentifier, existing);
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing =
|
||||||
|
ownedOutputsByTemplate.get(scriptRow.templateIdentifier) ??
|
||||||
|
new Set<string>();
|
||||||
|
existing.add(scriptRow.outputIdentifier);
|
||||||
|
ownedOutputsByTemplate.set(scriptRow.templateIdentifier, existing);
|
||||||
}
|
}
|
||||||
|
|
||||||
const loadedTemplates = await Promise.all(
|
const loadedTemplates = await Promise.all(
|
||||||
|
|||||||
@@ -221,7 +221,7 @@ export function InvitationScreen(): React.ReactElement {
|
|||||||
|
|
||||||
let isCurrent = true;
|
let isCurrent = true;
|
||||||
|
|
||||||
appService.engine.getOwnCommits(selectedInvitation.data)
|
appService.engine.findOwnCommits(selectedInvitation.data.invitationIdentifier)
|
||||||
.then((ownCommits) => {
|
.then((ownCommits) => {
|
||||||
if (!isCurrent) return;
|
if (!isCurrent) return;
|
||||||
|
|
||||||
@@ -723,10 +723,14 @@ export function InvitationScreen(): React.ReactElement {
|
|||||||
{outputTemplate?.name ?? output.outputIdentifier ?? `Output ${idx}`}
|
{outputTemplate?.name ?? output.outputIdentifier ?? `Output ${idx}`}
|
||||||
|
|
||||||
{/* Output description */}
|
{/* Output description */}
|
||||||
{outputTemplate?.description && ' - ' + compileCashAssemblyString(outputTemplate?.description ?? '', variables.reduce((acc, variable) => {
|
{outputTemplate?.description && ' - ' + compileCashAssemblyString({
|
||||||
acc[variable.variableIdentifier] = variable.value as XOInvitationVariableValue;
|
cashAssemblyText: outputTemplate?.description,
|
||||||
return acc;
|
variables: variables.reduce((acc, variable) => {
|
||||||
}, {} as Record<string, XOInvitationVariableValue>))}
|
acc[variable.variableIdentifier] = variable.value as XOInvitationVariableValue;
|
||||||
|
|
||||||
|
return acc;
|
||||||
|
}, {} as Record<string, XOInvitationVariableValue>)
|
||||||
|
})}
|
||||||
|
|
||||||
{/* Output value */}
|
{/* Output value */}
|
||||||
{outputSatoshis !== null && ` (${formatSatoshis(outputSatoshis)}${getFiatSuffix(outputSatoshis)})`}
|
{outputSatoshis !== null && ` (${formatSatoshis(outputSatoshis)}${getFiatSuffix(outputSatoshis)})`}
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ export const isInvitationRequirementsComplete = async (
|
|||||||
invitation: Invitation,
|
invitation: Invitation,
|
||||||
): Promise<boolean> => {
|
): Promise<boolean> => {
|
||||||
const missingRequirements = await invitation.getMissingRequirements();
|
const missingRequirements = await invitation.getMissingRequirements();
|
||||||
return !hasMissingRequirements(missingRequirements);
|
return !hasMissingRequirements(missingRequirements.templateRequirements);
|
||||||
};
|
};
|
||||||
|
|
||||||
// TODO: Move to engine in templates.ts
|
// TODO: Move to engine in templates.ts
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ export class RatesOracle extends BaseRates<RatesOracleEventMap> {
|
|||||||
private targetDenominatorUnitCode: string = 'BCH';
|
private targetDenominatorUnitCode: string = 'BCH';
|
||||||
private unsubscribeFromSettings: OffCallback | null = null;
|
private unsubscribeFromSettings: OffCallback | null = null;
|
||||||
|
|
||||||
private constructor(client: OracleClient, settings: SettingsService) {
|
public constructor(client: OracleClient, settings: SettingsService) {
|
||||||
super();
|
super();
|
||||||
|
|
||||||
this.client = client;
|
this.client = client;
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import type { XOInvitation } from "@xo-cash/types";
|
import type { XOInvitation } from "@xo-cash/types";
|
||||||
import { EventEmitter } from "./event-emitter.js";
|
import { EventEmitter } from "./event-emitter.js";
|
||||||
import { SSESession, type SSEvent } from "./sse-client.js";
|
// import { SSESession, type SSEvent } from "./sse-client.js";
|
||||||
import { decodeExtendedJson, encodeExtendedJson } from "./ext-json.js";
|
import { SSESession, type SSEvent } from "@xo-cash/utils";
|
||||||
|
import { deserializeInvitation, serializeInvitation } from "@xo-cash/engine";
|
||||||
|
|
||||||
export type SyncServerEventMap = {
|
export type SyncServerEventMap = {
|
||||||
connected: void;
|
connected: void;
|
||||||
@@ -38,7 +39,6 @@ export class SyncServer extends EventEmitter<SyncServerEventMap> {
|
|||||||
},
|
},
|
||||||
|
|
||||||
// Create our event bubblers
|
// Create our event bubblers
|
||||||
onMessage: (event: SSEvent) => this.emit("message", event),
|
|
||||||
onError: (error: unknown) =>
|
onError: (error: unknown) =>
|
||||||
this.emit(
|
this.emit(
|
||||||
"error",
|
"error",
|
||||||
@@ -48,6 +48,8 @@ export class SyncServer extends EventEmitter<SyncServerEventMap> {
|
|||||||
onConnected: () => this.emit("connected", undefined),
|
onConnected: () => this.emit("connected", undefined),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
this.sse.on("message", (event: SSEvent) => this.emit("message", event));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -63,7 +65,7 @@ export class SyncServer extends EventEmitter<SyncServerEventMap> {
|
|||||||
*/
|
*/
|
||||||
async disconnect(): Promise<void> {
|
async disconnect(): Promise<void> {
|
||||||
// Disconnect from the SSE Session
|
// Disconnect from the SSE Session
|
||||||
this.sse.close();
|
await this.sse.disconnect();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -81,9 +83,7 @@ export class SyncServer extends EventEmitter<SyncServerEventMap> {
|
|||||||
throw new Error(`Failed to get invitation: ${response.statusText}`);
|
throw new Error(`Failed to get invitation: ${response.statusText}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const invitation = decodeExtendedJson(await response.text()) as
|
const invitation = deserializeInvitation(await response.text());
|
||||||
| XOInvitation
|
|
||||||
| undefined;
|
|
||||||
return invitation;
|
return invitation;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,7 +96,7 @@ export class SyncServer extends EventEmitter<SyncServerEventMap> {
|
|||||||
// Send a POST request to the sync server
|
// Send a POST request to the sync server
|
||||||
const response = await fetch(`${this.baseUrl}/invitations`, {
|
const response = await fetch(`${this.baseUrl}/invitations`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: encodeExtendedJson(invitation),
|
body: serializeInvitation(invitation),
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
@@ -109,7 +109,7 @@ export class SyncServer extends EventEmitter<SyncServerEventMap> {
|
|||||||
|
|
||||||
// Read the returned JSON
|
// Read the returned JSON
|
||||||
// TODO: This should use zod to verify the response
|
// TODO: This should use zod to verify the response
|
||||||
const data = decodeExtendedJson(await response.text()) as XOInvitation;
|
const data = deserializeInvitation(await response.text());
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|||||||
58
src/utils/utxo-metadata.ts
Normal file
58
src/utils/utxo-metadata.ts
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import type { Engine } from "@xo-cash/engine";
|
||||||
|
import type { ScriptHashData, UnspentOutputData } from "@xo-cash/state";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Template and output identifiers resolved from script hash storage.
|
||||||
|
*/
|
||||||
|
export type UnspentOutputMetadata = {
|
||||||
|
templateIdentifier?: string;
|
||||||
|
outputIdentifier?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type UnspentOutputWithMetadata = UnspentOutputData & UnspentOutputMetadata;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds a lookup map from script hash to its stored metadata.
|
||||||
|
*/
|
||||||
|
export const buildScriptHashDataMap = async (
|
||||||
|
engine: Engine,
|
||||||
|
): Promise<Map<string, ScriptHashData>> => {
|
||||||
|
const scriptHashes = await engine.listScriptHashes();
|
||||||
|
const scriptHashDataByScriptHash = new Map<string, ScriptHashData>();
|
||||||
|
|
||||||
|
for (const scriptHashRow of scriptHashes) {
|
||||||
|
scriptHashDataByScriptHash.set(scriptHashRow.scriptHash, scriptHashRow);
|
||||||
|
}
|
||||||
|
|
||||||
|
return scriptHashDataByScriptHash;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves template/output metadata for a single UTXO via its script hash.
|
||||||
|
*/
|
||||||
|
export const getUnspentOutputMetadata = (
|
||||||
|
utxo: UnspentOutputData,
|
||||||
|
scriptHashDataByScriptHash: Map<string, ScriptHashData>,
|
||||||
|
): UnspentOutputMetadata => {
|
||||||
|
const scriptRow = scriptHashDataByScriptHash.get(utxo.scriptHash);
|
||||||
|
|
||||||
|
if (scriptRow === undefined) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
templateIdentifier: scriptRow.templateIdentifier,
|
||||||
|
outputIdentifier: scriptRow.outputIdentifier,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a UTXO enriched with template/output metadata from script hash storage.
|
||||||
|
*/
|
||||||
|
export const enrichUnspentOutput = (
|
||||||
|
utxo: UnspentOutputData,
|
||||||
|
scriptHashDataByScriptHash: Map<string, ScriptHashData>,
|
||||||
|
): UnspentOutputWithMetadata => ({
|
||||||
|
...utxo,
|
||||||
|
...getUnspentOutputMetadata(utxo, scriptHashDataByScriptHash),
|
||||||
|
});
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { expect, test, describe, beforeEach, afterEach } from "vitest";
|
import { expect, test, describe, beforeEach, afterEach } from "vitest";
|
||||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||||
import { tmpdir } from "node:os";
|
import { tmpdir } from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
|
|
||||||
@@ -98,6 +98,13 @@ const testCases: TestCase[] = [
|
|||||||
shouldThrow: false,
|
shouldThrow: false,
|
||||||
expectedData: {},
|
expectedData: {},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "export returns raw template json to stdout",
|
||||||
|
inputs: ["export", p2pkhTemplateIdentifier],
|
||||||
|
shouldThrow: false,
|
||||||
|
expectedData: {},
|
||||||
|
logs: [{ out: "\"name\":\"Wallet (P2PKH)\"" }],
|
||||||
|
},
|
||||||
// Error cases - subcommand
|
// Error cases - subcommand
|
||||||
{
|
{
|
||||||
name: "throws when no subcommand provided",
|
name: "throws when no subcommand provided",
|
||||||
@@ -124,6 +131,18 @@ const testCases: TestCase[] = [
|
|||||||
shouldThrow: true,
|
shouldThrow: true,
|
||||||
expectedEvent: "template.import.file_not_found",
|
expectedEvent: "template.import.file_not_found",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "throws when export called without template identifier",
|
||||||
|
inputs: ["export"],
|
||||||
|
shouldThrow: true,
|
||||||
|
expectedEvent: "template.export.identifier_missing",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "throws when export called with unknown template",
|
||||||
|
inputs: ["export", "unknown-template"],
|
||||||
|
shouldThrow: true,
|
||||||
|
expectedEvent: "template.export.not_found",
|
||||||
|
},
|
||||||
// Error cases - list category
|
// Error cases - list category
|
||||||
{
|
{
|
||||||
name: "throws when list category called without template identifier",
|
name: "throws when list category called without template identifier",
|
||||||
@@ -263,4 +282,42 @@ describe("template command", () => {
|
|||||||
process.chdir(originalCwd);
|
process.chdir(originalCwd);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("export prints exact engine template JSON to stdout", async () => {
|
||||||
|
const { io, capture } = createMockIO();
|
||||||
|
const expectedTemplate = await engine.getTemplate(p2pkhTemplateIdentifier);
|
||||||
|
expect(expectedTemplate).toBeDefined();
|
||||||
|
|
||||||
|
await handleTemplateCommand(
|
||||||
|
createCommandDeps(app, io),
|
||||||
|
["export", p2pkhTemplateIdentifier],
|
||||||
|
{},
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(capture.out[0]).toBe(JSON.stringify(expectedTemplate));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("export writes exact engine template JSON to file", async () => {
|
||||||
|
const outputFile = "exported-template.json";
|
||||||
|
const outputPath = path.join(tempDir, outputFile);
|
||||||
|
const { io } = createMockIO();
|
||||||
|
const expectedTemplate = await engine.getTemplate(p2pkhTemplateIdentifier);
|
||||||
|
expect(expectedTemplate).toBeDefined();
|
||||||
|
|
||||||
|
const originalCwd = process.cwd();
|
||||||
|
process.chdir(tempDir);
|
||||||
|
try {
|
||||||
|
const result = await handleTemplateCommand(
|
||||||
|
createCommandDeps(app, io),
|
||||||
|
["export", p2pkhTemplateIdentifier],
|
||||||
|
{ output: outputFile },
|
||||||
|
);
|
||||||
|
|
||||||
|
const exportedTemplate = readFileSync(outputPath, "utf8");
|
||||||
|
expect(exportedTemplate).toBe(JSON.stringify(expectedTemplate));
|
||||||
|
expect(result.outputFile).toBe(path.resolve(process.cwd(), outputFile));
|
||||||
|
} finally {
|
||||||
|
process.chdir(originalCwd);
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user