10 Commits
Author SHA1 Message Date
Emergent Reasons e39d6508cc Merge branch 'fix-pipeline-replacing-mermaid' into 'development'
Update pipeline to Node 24. Update Lerna. Update Vitepress to Beta. Replace...

See merge request GeneralProtocols/xo/stack!149
2026-08-08 11:06:50 +00:00
HarvmasterandEmergent Reasons 1c3e920c85 Update pipeline to Node 24. Update Lerna. Update Vitepress to Beta. Replace... 2026-08-08 11:06:49 +00:00
Emergent Reasons 53b7fb3aef Merge branch '105-fix-ci-using-expired-gitlab-token' into 'development'
Resolve "Fix CI using expired Gitlab token"

Closes #105

See merge request GeneralProtocols/xo/stack!147
2026-01-15 08:50:57 +00:00
HarvmasterandEmergent Reasons a029b43fc4 Resolve "Fix CI using expired Gitlab token" 2026-01-15 08:50:57 +00:00
Emergent Reasons f009cd31da Merge branch '103-support-wallet-offline-mode' into 'development'
Resolve "Support Wallet Offline Mode"

Closes #103

See merge request GeneralProtocols/xo/stack!146
2026-01-05 12:26:11 +00:00
HarvmasterandEmergent Reasons 38dc5be0f4 Resolve "Support Wallet Offline Mode" 2026-01-05 12:26:10 +00:00
Emergent Reasons b47a7c43ad Merge branch 'add-high-level-xo-article' into 'development'
Add high level xo article

See merge request GeneralProtocols/xo/stack!145
2025-12-21 16:45:08 +00:00
Emergent Reasons 3341340933 Add high level xo article 2025-12-21 16:45:08 +00:00
Jonathan Silverblood 2ed7002ebf Merge branch 'remote-js-yaml-as-top-level-depencency' into 'development'
Remove js-yaml as a dependency of stack but keep it as child dev-dependency

See merge request GeneralProtocols/xo/stack!144
2025-12-16 18:41:14 +00:00
Harvmaster 5057eb3421 Remove js-yaml as a dependency of stack but keep it as child dev-dependency 2025-12-16 22:02:23 +11:00
17 changed files with 4770 additions and 6013 deletions
+5 -3
View File
@@ -1,4 +1,4 @@
image: node:22 image: node:24
# We use stages for clarity of intent, and "needs" for dependencies and sequencing. # We use stages for clarity of intent, and "needs" for dependencies and sequencing.
# "needs" should work in parallel where acceptable, and get any artifacts directly from the source step. # "needs" should work in parallel where acceptable, and get any artifacts directly from the source step.
@@ -97,8 +97,10 @@ publish:development:
- git config --global user.email "${GITLAB_USER_EMAIL}" - git config --global user.email "${GITLAB_USER_EMAIL}"
- git config --global user.name "${GITLAB_USER_NAME}" - git config --global user.name "${GITLAB_USER_NAME}"
# Configure git to push with CI token # Configure git to push with CI token.
- git remote set-url origin "https://gitlab-ci-token:$GL_TOKEN@$CI_SERVER_HOST/$CI_PROJECT_PATH.git" # CI_REPOSITORY_URL uses the CI_JOB_TOKEN to form the repository URL, in the format "https://gitlab-ci-token:$CI_JOB_TOKEN@gitlab.example.com/my-group/my-project.git"
# The CI_JOB_TOKEN is short lived and only valid for the duration of the CI/CD job.
- git remote set-url origin "${CI_REPOSITORY_URL}"
# Ensure full Git history so Lerna can detect changes # Ensure full Git history so Lerna can detect changes
- git fetch --unshallow - git fetch --unshallow
+4176 -5727
View File
File diff suppressed because it is too large Load Diff
+10 -9
View File
@@ -54,25 +54,26 @@
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.10.0", "@eslint/js": "^9.10.0",
"@types/eslint__js": "^8.42.3", "@types/eslint__js": "^8.42.3",
"@typescript-eslint/eslint-plugin": "^8.5.0", "@typescript-eslint/eslint-plugin": "^8.66.0",
"@typescript-eslint/parser": "^8.5.0", "@typescript-eslint/parser": "^8.66.0",
"@vitest/coverage-v8": "^3.2.4", "@vitest/coverage-v8": "^3.2.4",
"eslint": "^9.10.0", "eslint": "^9.10.0",
"eslint-config-prettier": "^8.10.0", "eslint-config-prettier": "^8.10.0",
"eslint-plugin-prettier": "^5.2.1", "eslint-plugin-prettier": "^5.2.1",
"lerna": "^9.0.3", "lerna": "^10.0.0",
"madge": "^8.0.0", "madge": "^8.0.0",
"prettier": "^3.3.3", "prettier": "^3.3.3",
"typescript": "5.7.2", "typescript": "5.9.3",
"typescript-eslint": "^8.6.0", "typescript-eslint": "^8.66.0",
"vitest": "^3.2.4" "vitest": "^3.2.4"
}, },
"overrides": { "overrides": {
"vitepress": { "nx": {
"vite": "^7.1.10" "brace-expansion": "5.0.9"
}, },
"vitepress-plugin-mermaid": { "lerna": {
"vite": "^7.1.10" "js-yaml": "4.3.1",
"tar": "7.5.22"
} }
} }
} }
+3 -3
View File
@@ -17,13 +17,13 @@
"@monaco-editor/loader": "^1.5.0", "@monaco-editor/loader": "^1.5.0",
"@xocash/primitives": "*", "@xocash/primitives": "*",
"@xocash/stack": "*", "@xocash/stack": "*",
"monaco-editor": "^0.52.2" "monaco-editor": "^0.52.2",
"vitepress-mermaid-renderer": "^1.2.0"
}, },
"devDependencies": { "devDependencies": {
"typedoc": "^0.28.14", "typedoc": "^0.28.14",
"typedoc-plugin-markdown": "^4.3.2", "typedoc-plugin-markdown": "^4.3.2",
"typedoc-vitepress-theme": "^1.1.1", "typedoc-vitepress-theme": "^1.1.1",
"vitepress": "^1.6.4", "vitepress": "2.0.0-alpha.18"
"vitepress-plugin-mermaid": "^2.0.17"
} }
} }
+189 -192
View File
@@ -1,5 +1,4 @@
import { defineConfig } from 'vitepress'; import { defineConfig } from 'vitepress';
import { withMermaid } from 'vitepress-plugin-mermaid';
import typedocSidebar from '../api/typedoc-sidebar.json'; import typedocSidebar from '../api/typedoc-sidebar.json';
// Node imports for auto blog sidebar (works at docs/src/.vitepress) // Node imports for auto blog sidebar (works at docs/src/.vitepress)
@@ -39,8 +38,8 @@ function toPascalCase(str: string) {
.map((word) => { .map((word) => {
if (word.length === 0) return ''; if (word.length === 0) return '';
if (SPECIAL_CASES[word]) { if (word in SPECIAL_CASES) {
return SPECIAL_CASES[word]; return SPECIAL_CASES[word as keyof typeof SPECIAL_CASES];
} }
// Capitalize first letter, lowercase rest // Capitalize first letter, lowercase rest
@@ -114,210 +113,208 @@ function blogSidebar() {
} }
// https://vitepress.dev/reference/site-config // https://vitepress.dev/reference/site-config
export default withMermaid( export default defineConfig({
defineConfig({ outDir: '../dist',
outDir: '../dist', title: 'XO Stack',
title: 'XO Stack', description:
description: 'XO Stack: Building smart applications on the Bitcoin Cash Network',
'XO Stack: Building smart applications on the Bitcoin Cash Network', head: [
head: [ // Favicon.
// Favicon. ['link', { rel: 'icon', href: '/favicon.png' }],
['link', { rel: 'icon', href: '/favicon.png' }], // Basic OpenGraph tags
// Basic OpenGraph tags ['meta', { property: 'og:type', content: 'website' }],
['meta', { property: 'og:type', content: 'website' }], ['meta', { property: 'og:title', content: 'XO Stack' }],
['meta', { property: 'og:title', content: 'XO Stack' }], [
[ 'meta',
'meta', {
{ property: 'og:description',
property: 'og:description', content:
content: 'XO Stack: Building smart applications on the Bitcoin Cash Network',
'XO Stack: Building smart applications on the Bitcoin Cash Network',
},
],
[
'meta',
{
property: 'og:image',
content: 'https://stack.xo.cash/stack-opengraph.jpg',
},
],
['meta', { property: 'og:url', content: 'https://stack.xo.cash/' }],
// Optional additional tags
['meta', { property: 'og:site_name', content: 'XO Stack' }],
// Twitter Card tags (optional but recommended)
['meta', { name: 'twitter:card', content: 'summary_large_image' }],
['meta', { name: 'twitter:site', content: '@yourtwitterhandle' }],
],
themeConfig: {
// Set the logo
logo: {
light: '/logo-light.svg',
dark: '/logo-dark.svg',
}, },
],
[
'meta',
{
property: 'og:image',
content: 'https://stack.xo.cash/stack-opengraph.jpg',
},
],
['meta', { property: 'og:url', content: 'https://stack.xo.cash/' }],
// Enable search functionality. // Optional additional tags
// TODO: Re-enable once we release documentation. ['meta', { property: 'og:site_name', content: 'XO Stack' }],
/*
// Twitter Card tags (optional but recommended)
['meta', { name: 'twitter:card', content: 'summary_large_image' }],
['meta', { name: 'twitter:site', content: '@yourtwitterhandle' }],
],
themeConfig: {
// Set the logo
logo: {
light: '/logo-light.svg',
dark: '/logo-dark.svg',
},
// Enable search functionality.
// TODO: Re-enable once we release documentation.
/*
search: { search: {
provider: 'local', provider: 'local',
}, },
*/ */
// https://vitepress.dev/reference/default-theme-config // https://vitepress.dev/reference/default-theme-config
nav: [ nav: [
{ text: 'Home', link: '/' }, { text: 'Home', link: '/' },
// TODO: Re-enable once we release documentation // TODO: Re-enable once we release documentation
// { text: 'Documentation', link: '/quick-start' }, // { text: 'Documentation', link: '/quick-start' },
{ text: 'Blog', link: '/blog' }, { text: 'Blog', link: '/blog' },
{ text: 'Tools', link: '/tools/primitives' }, { text: 'Tools', link: '/tools/primitives' },
{ text: 'Playground', link: '/playground' }, { text: 'Playground', link: '/playground' },
],
sidebar: {
// Default Side Menu.
'/': [
{
text: 'Guide',
items: [
{ text: 'Quick Start', link: '/quick-start' },
{ text: 'Architecture', link: '/architecture' },
{ text: 'Best Practices', link: '/api-examples' },
{ text: 'Contributing', link: '/contributing' },
],
},
{
text: 'Frameworks',
items: [
{ text: 'Vue', link: '/frameworks/vue' },
{ text: 'React', link: '/frameworks/react' },
{ text: 'Svelte', link: '/frameworks/svelte' },
],
},
{
text: 'API',
items: convertNavToPascalCase(typedocSidebar),
},
], ],
// Side-menu for all routes under /tools/
sidebar: { '/tools/': [
// Default Side Menu. {
'/': [ text: 'XO Tools',
{ items: [
text: 'Guide', {
items: [ text: 'Primitives',
{ text: 'Quick Start', link: '/quick-start' }, link: '/tools/primitives',
{ text: 'Architecture', link: '/architecture' }, collapsed: false,
{ text: 'Best Practices', link: '/api-examples' }, items: [
{ text: 'Contributing', link: '/contributing' }, { text: 'Address', link: '/tools/primitives#address' },
], {
}, text: 'Block Header',
{ link: '/tools/primitives#block-header',
text: 'Frameworks', },
items: [ { text: 'Bytes', link: '/tools/primitives#bytes' },
{ text: 'Vue', link: '/frameworks/vue' }, {
{ text: 'React', link: '/frameworks/react' }, text: 'Encrypter',
{ text: 'Svelte', link: '/frameworks/svelte' }, link: '/tools/primitives#encrypter',
], },
}, {
{ text: 'Hasher',
text: 'API', link: '/tools/primitives#hasher',
items: convertNavToPascalCase(typedocSidebar), },
}, {
], text: 'HD Private Node',
// Side-menu for all routes under /tools/ link: '/tools/primitives#hd-private-node',
'/tools/': [ },
{ {
text: 'XO Tools', text: 'HD Public Node',
items: [ link: '/tools/primitives#hd-public-node',
{ },
text: 'Primitives', {
link: '/tools/primitives', text: 'Mnemonic',
collapsed: false, link: '/tools/primitives#mnemonic',
items: [ },
{ text: 'Address', link: '/tools/primitives#address' }, {
{ text: 'Private Key',
text: 'Block Header', link: '/tools/primitives#private-key',
link: '/tools/primitives#block-header', },
}, {
{ text: 'Bytes', link: '/tools/primitives#bytes' }, text: 'Public Key',
{ link: '/tools/primitives#public-key',
text: 'Encrypter', },
link: '/tools/primitives#encrypter', {
}, text: 'Satoshis',
{ link: '/tools/primitives#satoshis',
text: 'Hasher', },
link: '/tools/primitives#hasher', {
}, text: 'Script',
{ link: '/tools/primitives#script',
text: 'HD Private Node', },
link: '/tools/primitives#hd-private-node', {
}, text: 'Transaction',
{ link: '/tools/primitives#transaction',
text: 'HD Public Node', },
link: '/tools/primitives#hd-public-node', ],
}, },
{ {
text: 'Mnemonic', text: 'Stack',
link: '/tools/primitives#mnemonic', collapsed: false,
}, items: [
{ {
text: 'Private Key', text: 'Blockchain',
link: '/tools/primitives#private-key', link: '/tools/stack/blockchain',
}, items: [
{ {
text: 'Public Key', text: 'Electrum',
link: '/tools/primitives#public-key', link: '/tools/stack/blockchain#electrum',
}, },
{ ],
text: 'Satoshis', },
link: '/tools/primitives#satoshis', ],
}, },
{ ],
text: 'Script', },
link: '/tools/primitives#script',
},
{
text: 'Transaction',
link: '/tools/primitives#transaction',
},
],
},
{
text: 'Stack',
collapsed: false,
items: [
{
text: 'Blockchain',
link: '/tools/stack/blockchain',
items: [
{
text: 'Electrum',
link: '/tools/stack/blockchain#electrum',
},
],
},
],
},
],
},
],
// Blog sidebar (auto-generated)
'/blog/': blogSidebar(),
},
socialLinks: [
// { icon: 'github', link: 'https://gitlab.com/GeneralProtocols/xo/stack' },
{ icon: 'x', link: 'https://x.com/xo_bitcoincash' },
], ],
// Blog sidebar (auto-generated)
// This is the outline on the right-hand side of the page. '/blog/': blogSidebar(),
outline: {
level: [2, 4],
label: 'On this page',
},
}, },
// Set the dev and build targets to "esnext" socialLinks: [
// NOTE: We do this so that we can support top-level-await. // { icon: 'github', link: 'https://gitlab.com/GeneralProtocols/xo/stack' },
vite: { { icon: 'x', link: 'https://x.com/xo_bitcoincash' },
esbuild: { ],
// This is the outline on the right-hand side of the page.
outline: {
level: [2, 4],
label: 'On this page',
},
},
// Set the dev and build targets to "esnext"
// NOTE: We do this so that we can support top-level-await.
vite: {
esbuild: {
target: 'esnext',
},
build: {
target: 'esnext',
},
optimizeDeps: {
esbuildOptions: {
target: 'esnext', target: 'esnext',
}, },
build: { },
target: 'esnext', resolve: {
}, // Configure to use browser version of @xocash/stack
optimizeDeps: { conditions: ['browser', 'import', 'module', 'default'],
esbuildOptions: { },
target: 'esnext', // SSR has its own separate ssr.resolve.conditions that must be explicitly set since not follow global resolve conditions.
}, ssr: {
},
resolve: { resolve: {
// Configure to use browser version of @xocash/stack // Configure to use browser version of @xocash/stack
conditions: ['browser', 'import', 'module', 'default'], conditions: ['browser', 'import', 'module', 'default'],
}, },
// SSR has its own separate ssr.resolve.conditions that must be explicitly set since not follow global resolve conditions.
ssr: {
resolve: {
// Configure to use browser version of @xocash/stack
conditions: ['browser', 'import', 'module', 'default'],
},
},
}, },
}), },
); });
+50 -4
View File
@@ -1,15 +1,61 @@
// https://vitepress.dev/guide/custom-theme import { h, nextTick, watch } from 'vue';
import type { Theme } from 'vitepress'; import type { Theme } from 'vitepress';
import { useData } from 'vitepress';
import DefaultTheme from 'vitepress/theme'; import DefaultTheme from 'vitepress/theme';
import Layout from './Layout.vue'; import Layout from './Layout.vue';
import './style.css'; import './style.css';
import './custom.css'; import './custom.css';
import './tools.css'; import './tools.css';
import './mermaid-overrides.css'; import './mermaid-overrides.css';
import './mermaid-lightbox.client';
import { createMermaidRenderer } from 'vitepress-mermaid-renderer';
export default { export default {
extends: DefaultTheme, extends: DefaultTheme,
Layout,
enhanceApp({ _app, _router, _siteData }) {}, Layout: () => {
const { isDark, localeIndex } = useData();
const initMermaid = () => {
const mermaidRenderer = createMermaidRenderer({
theme: isDark.value ? 'dark' : 'forest',
});
mermaidRenderer.setToolbar({
showLanguageLabel: false,
downloadFormat: 'svg',
fullscreenMode: 'browser',
desktop: {
copyCode: 'enabled',
toggleFullscreen: 'enabled',
resetView: 'enabled',
zoomOut: 'enabled',
zoomIn: 'enabled',
zoomLevel: 'enabled',
download: 'enabled',
},
fullscreen: {
copyCode: 'disabled',
toggleFullscreen: 'enabled',
resetView: 'disabled',
zoomLevel: 'disabled',
download: 'enabled',
},
});
};
nextTick(initMermaid);
watch(
() => [isDark.value, localeIndex.value] as const,
() => {
initMermaid();
},
);
return h(Layout);
},
enhanceApp() {},
} satisfies Theme; } satisfies Theme;
@@ -0,0 +1,191 @@
---
title: 'What Makes the XO Wallet Different'
date: 2025-12-20
description: A big picture look at how the XO Wallet aims to change the way people interact with Bitcoin Cash apps, focusing on safety, clarity, and user control.
author: Saqib Noor
tags: [wallet, general audience]
---
# What Makes the XO Wallet Different?
## Introduction
Wallets are the primary way people interact with crypto ecosystems, from everyday value transfers to more complex decentralised applications. For Bitcoin Cash, a peer to peer electronic cash system, wallets are how people directly send, receive, and understand value without intermediaries. They are the bridge between users, apps, and the blockchain itself. Yet for all their importance, wallets have changed very little in how they help users understand what is actually happening when they interact with an app.
This article explains what makes the **XO Wallet** different. It does not dive deep into technical details or code. Instead, it looks at the bigger picture: how wallets can move beyond simply signing transactions, how understanding and safety can be improved, and why this matters as Bitcoin Cash applications become more powerful and more complex.
## A wallet that understands what you are doing!
Most crypto wallets today are very good at one thing: signing transactions. They are much less good at understanding *why* you are signing them.
When you interact with an app, a DeFi protocol, or even a simple token transfer, the wallet often shows you raw data, script hashes, or vague warnings. Users are expected to trust the app, trust the website, and hope nothing goes wrong.
The XO Wallet is built around a different idea.
Instead of being blind, the wallet is designed to **understand the intent of an action**, not just the bytes of a transaction.
---
## From Signing Transactions to Understanding Intent
The key difference comes from **templates**, which act as a cornerstone of how the XO Wallet understands and verifies actions.
A template is a shared description of:
- What kind of actions are available
- Who is involved
- What funds or tokens are at stake
- What rules apply
- What state must be tracked over time
Templates are not arbitrary or hidden. They are designed to be visible, reviewable, and trusted over time through auditing, reputation, and community scrutiny. This gives the wallet a reliable basis for understanding what an action is meant to do.
With templates, the wallet is no longer guessing. It knows whether you are:
- Receiving tokens
- Locking funds into a specific contract and understanding what that contract allows
- Opening or closing a position
- Signing a message
- Transferring ownership
That means the wallet can explain actions in **human terms**, before you approve them, and verify that what is happening matches the intent you were shown.
### Trust Once, Not Every Time
A key difference between templates and traditional decentralised apps is **how often trust is required**.
In today's DeFi models, users implicitly trust every website, interface update, and transaction request they interact with. This trust is granted repeatedly, often by habit rather than careful review.
Templates change this dynamic.
A template is something that needs to be trusted **once**, not at every interaction. Once a template has been reviewed, audited, and understood, the wallet can rely on it consistently to interpret actions, and enforce rules.
This mirrors how people already think about wallets themselves. You choose a wallet carefully, then rely on it repeatedly without re-evaluating it on every transaction.
Templates extend this trust model to application logic, concentrating trust into fewer, more stable components. This gives users and the community more room for scrutiny, stronger incentives for correctness, and a safer foundation than repeatedly trusting changing front ends or opaque transaction requests.
---
## How This Changes the Flow
Instead of apps directly asking wallets to sign opaque transactions, the flow becomes structured and understandable.
```mermaid
flowchart LR
App --> Template
subgraph XO Wallet-Template interaction
Template -->|human readable intent| Wallet
Wallet -->|trusted source| Template
end
User --> Wallet
App[Application]
Template[Template]
Wallet[XO Wallet]
User[User]
```
The wallet is no longer a passive signer.
It becomes an active interpreter between apps and users.
---
## State That Does Not Disappear
A common pain point in crypto is lost context.
You open a position, receive a token, or lock funds, then later:
- Change wallets
- Reinstall an app
- Lose track of where the funds came from
In much of today’s crypto ecosystem, users implicitly trust applications to track this state for them. The app remembers what a position represents, which coins belong to which protocol, and how everything fits together. If that app disappears, changes direction, or is no longer maintained, having the raw on chain data alone may not be enough to continue using the protocol in a meaningful way.
To function properly, they often need visibility into a user’s coins, balances, and activity so they can decide what to spend, what to lock, and how to construct transactions. This requirement also pushes apps to be deeply invasive.
XO approaches this differently.
XO treats **state as a first class concept**, managed by the wallet itself.
The wallet tracks which outputs belong to which templates, and what they represent. This allows it to:
- Show meaningful balances
- Restore context after a restart
- Understand ownership over time
- Avoid accidental loss of access
Managing and preserving this state is a significant responsibility, arguably as important as private key management itself. Losing state can mean losing understanding, control, or even access, even if the underlying funds still exist.
In the XO model, applications can still manage state if they choose to, but users are no longer forced to rely on them. By default, users remain self custodial not only of their keys, but of their wallet state as well, with options for secure backup, recovery, and continuity built into the wallet rather than delegated elsewhere.
For users, this feels simple. For wallets, it is a major step forward.
---
## Clear Ownership, Clear Responsibility
XO templates define ownership explicitly.
Instead of vague ideas of “this UTXO belongs to you”, the wallet knows:
- Which conditions control which output
- What actions that ownership enables
- What value is associated with that ownership
A simple example helps make this clearer.
Imagine you participate in a liquidity pool. The funds you contribute are locked into a shared pool, and the UTXO representing your position is clearly of interest to you. However, its value is not obvious in the same way as a simple coin balance. It depends on pool size, relative contributions, fees, and changing conditions over time.
With templates, this ambiguity is addressed directly. The template defines what ownership means in this context. It can include built in calculations that estimate your share of the pool’s value at any given moment. The wallet can then present this information clearly, without guessing or relying on external apps to explain it.
This clarity allows the wallet to:
- Estimate balances more accurately
- Show expected outcomes before actions
- Prevent actions that would violate the ownership model defined by the template
It also lays the groundwork for better privacy and smarter coin selection in the future, since the wallet understands not just which coins exist, but what they represent and how they should be treated.
---
## Designed for Normal People, Not Just Developers
Although the XO wallet is powerful under the hood, the goal is not to expose complexity to the everyday user.
The XO Wallet aims to:
- Explain actions in plain language
- Show only what matters at the right time
- Reduce scary jargon and warnings, replace them with clarity and guides
- Make advanced Bitcoin Cash applications feel natural to use
This requires more than good engineering. It requires a thoughtful, empowering user interface that helps people feel confident, informed, and in control. To succeed, wallets must compete not only with other crypto products, but with the best experiences people already expect and demand from modern, traditional financial applications.
You should not need to understand raw transaction data, unfamiliar warnings, or confusing approval screens to feel confident. A well designed wallet should feel as intuitive and dependable as any trusted financial tool, while preserving the openness and self custody that make peer to peer systems truly valuable and loved.
---
## A Foundation, Not Just a Product
The XO Wallet is not just another wallet.
It is a reference implementation of a broader idea:
- Wallets should be active interpreters, not passive signers
- Wallets should be smart enough to help users understand transactions in an intuitive, human way
- Trust should be placed in well-vetted, stable templates rather than in websites, domains, or opaque front ends
- Safety should come from clear structure and shared rules, not from blind trust in external applications
In this model, decentralisation is strengthened rather than weakened. Users are less dependent on specific apps continuing to exist, and more reliant on open, reviewable definitions of intent that wallets can understand and enforce.
This is how the XO Stack moves from vision to reality, one layer at a time.
---
## What Comes Next
This post focuses on the *why*.
Future articles will explore:
- How wallets choose which templates to trust
- How the wallet handles state
- How different apps can interoperate safely
- How this model supports more complex use cases without sacrificing user control
The goal is simple:
make powerful Bitcoin Cash applications usable, understandable, and safe for everyone.
+12 -3
View File
@@ -36,20 +36,26 @@ export class Encrypter {
...opts, ...opts,
}; };
// Something about the browser crypto API. It needs a "clean" Uint8Array, where TS could see the construction or something
const cleanKey = new Uint8Array(key);
// Create a key derivation key // Create a key derivation key
const keyMaterialBase = await crypto.subtle.importKey( const keyMaterialBase = await crypto.subtle.importKey(
'raw', 'raw',
key, cleanKey,
'PBKDF2', 'PBKDF2',
false, false,
['deriveBits', 'deriveKey'], ['deriveBits', 'deriveKey'],
); );
// Something about the browser crypto API. It needs a "clean" Uint8Array, where TS could see the construction or something
const cleanSalt = new Uint8Array(encryptionOpts.salt);
// Derive the actual encryption key // Derive the actual encryption key
const derivedKey = await crypto.subtle.deriveKey( const derivedKey = await crypto.subtle.deriveKey(
{ {
name: 'PBKDF2', name: 'PBKDF2',
salt: encryptionOpts.salt, salt: cleanSalt,
iterations: encryptionOpts.iterations, iterations: encryptionOpts.iterations,
hash: 'SHA-256', hash: 'SHA-256',
}, },
@@ -87,6 +93,9 @@ export class Encrypter {
// Generate random IV // Generate random IV
const iv = crypto.getRandomValues(new Uint8Array(this.opts.ivLength)); const iv = crypto.getRandomValues(new Uint8Array(this.opts.ivLength));
// Something about the browser crypto API. It needs a "clean" Uint8Array, where TS could see the construction or something
const cleanData = new Uint8Array(data);
// Encrypt the data // Encrypt the data
const encryptedData = await crypto.subtle.encrypt( const encryptedData = await crypto.subtle.encrypt(
{ {
@@ -94,7 +103,7 @@ export class Encrypter {
iv, iv,
}, },
this.key, this.key,
data, cleanData,
); );
// Combine IV and encrypted data // Combine IV and encrypted data
+1 -1
View File
@@ -41,7 +41,7 @@
"@generalprotocols/oracle-client": "^0.0.1-development.11878773826", "@generalprotocols/oracle-client": "^0.0.1-development.11878773826",
"@xocash/primitives": "*", "@xocash/primitives": "*",
"async-mutex": "^0.5.0", "async-mutex": "^0.5.0",
"better-sqlite3": "^11.8.1", "better-sqlite3": "^13.0.3",
"idb": "8.0.3", "idb": "8.0.3",
"json-to-graphql-query": "^2.3.0", "json-to-graphql-query": "^2.3.0",
"msgpackr": "^1.11.2", "msgpackr": "^1.11.2",
+2 -3
View File
@@ -6,10 +6,9 @@ export const MetadataRegistrySchema = z
description: z.string().optional(), description: z.string().optional(),
uris: z uris: z
.object({ .object({
// Since 'icon' and 'web' are strongly recommended uri identifiers(https://github.com/bitjson/chip-bcmr?tab=readme-ov-file#recommended-uri-identifiers) // 'icon' and 'web' are strongly recommended uri identifiers(https://github.com/bitjson/chip-bcmr?tab=readme-ov-file#recommended-uri-identifiers)
// We require it as non optional.
icon: z.url(), icon: z.url(),
web: z.url(), web: z.url().optional(),
}) })
// Allows any other keys with any values. // Allows any other keys with any values.
.catchall(z.unknown()), .catchall(z.unknown()),
@@ -192,17 +192,17 @@ export class BlockchainElectrum extends BaseBlockchain<
} }
async fetchUnspents(address: string) { async fetchUnspents(address: string) {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
// Define the cache key. // Define the cache key.
const cacheKey = `addressUnspents.${address}`; const cacheKey = `addressUnspents.${address}`;
// Attempt to get the address unspents from the cache or fetch them if not available. // Attempt to get the address unspents from the cache or fetch them if not available.
const addressUnspents = await this.store.getOrSet(cacheKey, async () => { const addressUnspents = await this.store.getOrSet(cacheKey, async () => {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
return await fetchUnspentTransactionOutputs( return await fetchUnspentTransactionOutputs(
this.electrumClient, this.electrumClient,
address, address,
@@ -249,17 +249,17 @@ export class BlockchainElectrum extends BaseBlockchain<
} }
async fetchTransaction(txHash: string) { async fetchTransaction(txHash: string) {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
// Define the cache key. // Define the cache key.
const cacheKey = `transactions.${txHash}`; const cacheKey = `transactions.${txHash}`;
// Attempt to get the transaction hex from the cache or fetch it if not available. // Attempt to get the transaction hex from the cache or fetch it if not available.
const transactionRaw = await this.store.getOrSet(cacheKey, async () => { const transactionRaw = await this.store.getOrSet(cacheKey, async () => {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
const txHex = await fetchTransaction(this.electrumClient, txHash); const txHex = await fetchTransaction(this.electrumClient, txHash);
return Transaction.fromHex(txHex).toRaw(); return Transaction.fromHex(txHex).toRaw();
}); });
@@ -272,17 +272,17 @@ export class BlockchainElectrum extends BaseBlockchain<
} }
async fetchAddressHistory(address: string) { async fetchAddressHistory(address: string) {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
// Define the cache key. // Define the cache key.
const cacheKey = `addressHistory.${address}`; const cacheKey = `addressHistory.${address}`;
// Attempt to get the transaction history from the cache or fetch them if not available. // Attempt to get the transaction history from the cache or fetch them if not available.
const addressHistory = await this.store.getOrSet(cacheKey, async () => { const addressHistory = await this.store.getOrSet(cacheKey, async () => {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
return await fetchHistory(this.electrumClient, address); return await fetchHistory(this.electrumClient, address);
}); });
@@ -305,17 +305,17 @@ export class BlockchainElectrum extends BaseBlockchain<
} }
async fetchBlockHeader(blockHeight: number) { async fetchBlockHeader(blockHeight: number) {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
// Define the cache key. // Define the cache key.
const cacheKey = `blockHeader.${blockHeight}`; const cacheKey = `blockHeader.${blockHeight}`;
// Attempt to get the transaction history from the cache or fetch them if not available. // Attempt to get the transaction history from the cache or fetch them if not available.
const blockHeaderRaw = await this.store.getOrSet(cacheKey, async () => { const blockHeaderRaw = await this.store.getOrSet(cacheKey, async () => {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
const headerHex = await fetchBlockHeaderFromBlockHeight( const headerHex = await fetchBlockHeaderFromBlockHeight(
this.electrumClient, this.electrumClient,
blockHeight, blockHeight,
@@ -333,15 +333,15 @@ export class BlockchainElectrum extends BaseBlockchain<
// TODO: ElectrumClient provides a chainHeight property that is populated after a `blockchain.headers.subscribe` call. // TODO: ElectrumClient provides a chainHeight property that is populated after a `blockchain.headers.subscribe` call.
// We may be able to leverage this side-effect to avoid fetching the chain tip. // We may be able to leverage this side-effect to avoid fetching the chain tip.
async fetchChainTip() { async fetchChainTip() {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
// If we don't currently have a block height, fetch the current chain tip. // If we don't currently have a block height, fetch the current chain tip.
// NOTE: We don't use our cache here because the key will be the same and so on-boot, we will have a stale value. // NOTE: We don't use our cache here because the key will be the same and so on-boot, we will have a stale value.
if (!this.blockHeight) { if (!this.blockHeight) {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
const chainTip = await fetchCurrentChainTip(this.electrumClient); const chainTip = await fetchCurrentChainTip(this.electrumClient);
this.blockHeight = chainTip.height; this.blockHeight = chainTip.height;
+1
View File
@@ -15,6 +15,7 @@ export * from './wallet/index.js';
// For node-only providers, export these from index.node.ts. // For node-only providers, export these from index.node.ts.
export * from './bcmr/bcmr-composite.js'; export * from './bcmr/bcmr-composite.js';
export * from './bcmr/bcmr-http.js'; export * from './bcmr/bcmr-http.js';
export * from './bcmr/bcmr-helpers.js';
export * from './blockchain/blockchain-electrum.js'; export * from './blockchain/blockchain-electrum.js';
export * from './blockchain/blockchain-chaingraph.js'; export * from './blockchain/blockchain-chaingraph.js';
export * from './storage/store-remote-http.js'; export * from './storage/store-remote-http.js';
+26 -6
View File
@@ -1,6 +1,11 @@
import { BaseRates } from './base-rates.js'; import { BaseRates } from './base-rates.js';
import { UUIDV7 } from '../utils/uuid.js'; import { UUIDV7 } from '../utils/uuid.js';
export type CachedRate = {
price: number;
timestamp: number;
};
/** /**
* A composite rate adapter that combines rates from multiple rate sources * A composite rate adapter that combines rates from multiple rate sources
* using a configurable policy. * using a configurable policy.
@@ -13,7 +18,16 @@ export class RatesComposite extends BaseRates {
private availablePairs: Set<string> = new Set(); private availablePairs: Set<string> = new Set();
// Cache of the latest rates from each adapter // Cache of the latest rates from each adapter
private rateCache: Map<string, Map<string, Map<string, number>>> = new Map(); /**
* Cache of the latest rates from each adapter
*
* The cache is a nested map of:
* - denominatorCode -> numeratorCode -> adapterId -> CachedRate
*
* Eg: BCH -> USD -> 1 (Oracles) -> { price: 100, timestamp: 1714857600 }
*/
private rateCache: Map<string, Map<string, Map<string, CachedRate>>> =
new Map();
// Off callbacks for unsubscribing from events // Off callbacks for unsubscribing from events
private unsubscribeFunctions: Map<string, () => void> = new Map(); private unsubscribeFunctions: Map<string, () => void> = new Map();
@@ -210,7 +224,7 @@ export class RatesComposite extends BaseRates {
// Store the rate in the cache // Store the rate in the cache
const rateMap = denomMap.get(numeratorUnitCode)!; const rateMap = denomMap.get(numeratorUnitCode)!;
rateMap.set(adapterId, price); rateMap.set(adapterId, { price, timestamp: Date.now() });
// Add pair to available pairs // Add pair to available pairs
this.availablePairs.add(`${numeratorUnitCode}/${denominatorUnitCode}`); this.availablePairs.add(`${numeratorUnitCode}/${denominatorUnitCode}`);
@@ -225,12 +239,19 @@ export class RatesComposite extends BaseRates {
// Process each numerator currency // Process each numerator currency
for (const [numerator, rateMap] of numeratorMap.entries()) { for (const [numerator, rateMap] of numeratorMap.entries()) {
// Go through our adapters in order, plucking the rate for each adapter // Go through our adapters in order, plucking the rate for each adapter
const rates = this.adapters const cachedRates = this.adapters
// First, get the Cached rate for each adapter
.map(({ id }) => rateMap.get(id)) .map(({ id }) => rateMap.get(id))
.filter((rate) => rate !== undefined); // Then, filter out any undefined rates (service is down, rate limit, etc.)
.filter((rate) => rate !== undefined)
// Then, filter out any rates that are older than the refresh interval so we don't emit stale rates
// it's up to the client to hold onto "stale" rates if they need them, rather than us mixing old and new rates without disclosing it.
.filter(
(rate) => rate.timestamp > Date.now() - this.refreshIntervalMs,
);
// Apply policy to get combined rate // Apply policy to get combined rate
const combinedRate = this.policy(rates); const combinedRate = this.policy(cachedRates.map(({ price }) => price));
// Only emit if we have a valid rate // Only emit if we have a valid rate
if (combinedRate !== null) { if (combinedRate !== null) {
@@ -244,7 +265,6 @@ export class RatesComposite extends BaseRates {
} }
} }
} }
export type RatesCompositePolicy = (rates: number[]) => number | null; export type RatesCompositePolicy = (rates: number[]) => number | null;
/** /**
+20 -10
View File
@@ -15,20 +15,27 @@ export type StoreEvents = {
clear: undefined; clear: undefined;
}; };
export abstract class BaseStorage { /**
* Abstract base class for storage implementations.
*
* @template E The events type for stores created by this storage.
* Must extend StoreEvents (at least includes base events).
* Defaults to StoreEvents for base type hints.
*/
export abstract class BaseStorage<E extends StoreEvents = StoreEvents> {
abstract listStores(): Promise<Array<string>>; abstract listStores(): Promise<Array<string>>;
abstract createStore( abstract createStore<T = unknown>(
storeName: string, storeName: string,
opts: StorageOpts, opts: StorageOpts,
): Promise<BaseStore>; ): Promise<BaseStore<T, E>>;
abstract getStore( abstract getStore<T = unknown>(
storeName: string,
opts?: StorageOpts,
): Promise<BaseStore<T, E> | null>;
abstract createOrGetStore<T = unknown>(
storeName: string, storeName: string,
opts: StorageOpts, opts: StorageOpts,
): Promise<BaseStore | null>; ): Promise<BaseStore<T, E>>;
abstract createOrGetStore(
storeName: string,
opts: StorageOpts,
): Promise<BaseStore>;
abstract deleteStore(storeName: string): Promise<void>; abstract deleteStore(storeName: string): Promise<void>;
abstract deleteDatabase(): Promise<void>; abstract deleteDatabase(): Promise<void>;
} }
@@ -79,7 +86,10 @@ export type StoreValueProxy<T> = {
* } * }
* ``` * ```
*/ */
export abstract class BaseStore<K = unknown> extends EventEmitter<StoreEvents> { export abstract class BaseStore<
K = unknown,
E extends StoreEvents = StoreEvents,
> extends EventEmitter<E> {
/** /**
* Returns an array of all keys in the store. * Returns an array of all keys in the store.
*/ */
+45 -12
View File
@@ -1,4 +1,9 @@
import { BaseStorage, BaseStore, StorageOpts } from './base-store.js'; import {
BaseStorage,
BaseStore,
StorageOpts,
StoreEvents,
} from './base-store.js';
import { SSESession } from '../utils/index.js'; import { SSESession } from '../utils/index.js';
import { import {
Bytes, Bytes,
@@ -15,13 +20,18 @@ export type EncrptedStoreOpts = StorageOpts & {
encrypter: Encrypter; encrypter: Encrypter;
}; };
export type StoreRemoteHTTPEvents = StoreEvents & {
connected: undefined;
disconnected: undefined;
};
/** /**
* A storage adapter for a remote storage server. * A storage adapter for a remote storage server.
* *
* All data sent to the server is first packed using MessagePack and then encrypted using the provided encrypter and then packed again using MessagePack. * All data sent to the server is first packed using MessagePack and then encrypted using the provided encrypter and then packed again using MessagePack.
* The requests are signed using the provided private key and the timestamp of the request to mitigate replay attacks and to authenticate the request. * The requests are signed using the provided private key and the timestamp of the request to mitigate replay attacks and to authenticate the request.
*/ */
export class StorageRemoteHTTP extends BaseStorage { export class StorageRemoteHTTP extends BaseStorage<StoreRemoteHTTPEvents> {
/** /**
* Creates a new StorageRemoteHTTP instance. * Creates a new StorageRemoteHTTP instance.
* *
@@ -33,7 +43,7 @@ export class StorageRemoteHTTP extends BaseStorage {
return storage; return storage;
} }
private stores: Map<string, StoreRemoteHTTP> = new Map(); private stores: Map<string, StoreRemoteHTTP<any>> = new Map();
constructor(protected baseURL: string) { constructor(protected baseURL: string) {
super(); super();
@@ -45,7 +55,9 @@ export class StorageRemoteHTTP extends BaseStorage {
* @param storeName The name of the store to get. * @param storeName The name of the store to get.
* @returns The store or null if it does not exist. * @returns The store or null if it does not exist.
*/ */
async getStore(storeName: string): Promise<StoreRemoteHTTP | null> { async getStore<T = unknown>(
storeName: string,
): Promise<StoreRemoteHTTP<T> | null> {
return this.stores.get(storeName) || null; return this.stores.get(storeName) || null;
} }
@@ -56,8 +68,11 @@ export class StorageRemoteHTTP extends BaseStorage {
* @param opts The options for the store. This includes the private key and encrypter. * @param opts The options for the store. This includes the private key and encrypter.
* @returns The created store. * @returns The created store.
*/ */
async createStore(storeName: string, opts: EncrptedStoreOpts): Promise<StoreRemoteHTTP> { async createStore<T = unknown>(
const store = await StoreRemoteHTTP.from( storeName: string,
opts: EncrptedStoreOpts,
): Promise<StoreRemoteHTTP<T>> {
const store = await StoreRemoteHTTP.from<T>(
this.baseURL, this.baseURL,
opts.privateKey, opts.privateKey,
opts.encrypter, opts.encrypter,
@@ -73,7 +88,10 @@ export class StorageRemoteHTTP extends BaseStorage {
* @param opts The options for the store. This includes the private key and encrypter. * @param opts The options for the store. This includes the private key and encrypter.
* @returns The created or existing store. * @returns The created or existing store.
*/ */
async createOrGetStore(storeName: string, opts: EncrptedStoreOpts): Promise<StoreRemoteHTTP> { async createOrGetStore<T = unknown>(
storeName: string,
opts: EncrptedStoreOpts,
): Promise<StoreRemoteHTTP<T>> {
const store = await this.getStore(storeName); const store = await this.getStore(storeName);
if (store) { if (store) {
return store; return store;
@@ -110,12 +128,15 @@ export class StorageRemoteHTTP extends BaseStorage {
} }
} }
export class StoreRemoteHTTP extends BaseStore { export class StoreRemoteHTTP<T = unknown> extends BaseStore<
static async from( T,
StoreRemoteHTTPEvents
> {
static async from<T = unknown>(
baseURL: string, baseURL: string,
privateKey: PrivateKey, privateKey: PrivateKey,
encrypter: Encrypter, encrypter: Encrypter,
) { ): Promise<StoreRemoteHTTP<T>> {
const store = new this(baseURL, privateKey, encrypter); const store = new this(baseURL, privateKey, encrypter);
await store.subscribeEvents(); await store.subscribeEvents();
@@ -235,6 +256,12 @@ export class StoreRemoteHTTP extends BaseStore {
}); });
}, },
onReconnect: createSSESessionOptions, onReconnect: createSSESessionOptions,
onConnected: () => {
this.emit('connected', undefined);
},
onDisconnected: () => {
this.emit('disconnected', undefined);
},
...options, ...options,
}); });
} }
@@ -270,10 +297,16 @@ export class StoreRemoteHTTP extends BaseStore {
'X-Timestamp': timestamp.toString(), 'X-Timestamp': timestamp.toString(),
}; };
const requestOptions = { const body = payload ? pack(payload) : pack({});
const bodyBuffer = new Uint8Array(body.buffer);
const requestOptions: RequestInit = {
method: 'POST', method: 'POST',
headers, headers,
body: payload ? pack(payload) : pack({}), // Because we support the DOM types, it doesnt register this UInt8Array as an acceptable BodyInit, so we need to cast it to unknown.
// Could be fixed in a later version of typescript, but there are build issues atm.
// TODO: (not really, unless we intend to use this code) Remove the type cast.
body: bodyBuffer as unknown as BodyInit,
}; };
// Use the URL class to compile the full path. // Use the URL class to compile the full path.
@@ -4,19 +4,18 @@
// However, Chaingraph backend is currently broken for many queries, so let's not do this yet. // However, Chaingraph backend is currently broken for many queries, so let's not do this yet.
import { beforeAll, describe, it, expect } from 'vitest'; import { beforeAll, describe, it, expect } from 'vitest';
import { import { BaseBlockchain, BlockchainElectrum } from '../../src/index.js';
BaseBlockchain,
BlockchainChaingraph,
BlockchainElectrum,
} from '../../src/index.js';
const adapters: Record< const adapters: Record<
string, string,
() => Promise<BaseBlockchain<unknown, unknown>> () => Promise<BaseBlockchain<unknown, unknown>>
> = { > = {
chaingraph: async () => { // Commenting out since the chaingraph endopoints we are hitting are currently broken.
return await BlockchainChaingraph.from(); // demo won't allow non-browser clients
}, // Pat's server isn't responding to block height requests correctly (or we are using an old version, which the demo server is also running).
// chaingraph: async () => {
// return await BlockchainChaingraph.from();
// },
electrum: async () => { electrum: async () => {
return await BlockchainElectrum.from(); return await BlockchainElectrum.from();
}, },
@@ -59,7 +58,7 @@ describe.each(Object.entries(adapters))('%s Adapter', (name, createAdapter) => {
}); });
it(`${name}.fetchBlockHeader() `, async () => { it(`${name}.fetchBlockHeader() `, async () => {
const result = await blockchain.fetchBlockHeader(testBlockHeight); const result = await blockchain.fetchBlockHeader(1);
expect(result).toBeDefined(); expect(result).toBeDefined();
expect(result.toHex()).toBeTypeOf('string'); expect(result.toHex()).toBeTypeOf('string');
@@ -6,7 +6,7 @@ import {
monitorSyncTipsSchema, monitorSyncTipsSchema,
} from '../../src/blockchain/blockchain-chaingraph-helpers.js'; } from '../../src/blockchain/blockchain-chaingraph-helpers.js';
const chaingraphServer = 'https://demo.chaingraph.cash/v1/graphql'; const chaingraphServer = 'https://gql.chaingraph.pat.mn/v1/graphql';
describe('GraphQLClient', () => { describe('GraphQLClient', () => {
const graphQLClient = new GraphQLClient(chaingraphServer); const graphQLClient = new GraphQLClient(chaingraphServer);