Skip to content

A research prototype demonstrating programmable Ark Layer 2 transactions, using Taproot to enable trustless atomic swaps and stateful digital assets (SatoshiKoi)

License

Notifications You must be signed in to change notification settings

jgmcalpine/ArkSwap

Repository files navigation

Important

🚨 WARNING: EXPERIMENTAL PROOF OF CONCEPT β€” DO NOT USE WITH REAL FUNDS 🚨

This software is strictly for EDUCATIONAL PURPOSES ONLY. It is designed exclusively for a local Bitcoin Regtest environment.

  • DO NOT attempt to use this on Bitcoin Mainnet.
  • DO NOT send real Bitcoin or real Ark VTXOs to any address generated by this application.
  • DO NOT input real private keys. This application stores keys insecurely in the browser's localStorage.

This code is UNAUDITED and contains intentional architectural shortcuts for demonstration purposes. Using this software with real value will result in TOTAL LOSS OF FUNDS.

ArkSwap & SatoshiKoi

A Reference Implementation for Programmable Ark Transactions.

License TypeScript Stack Assurance

🌊 Overview

This repository is a research prototype designed to explore the limits of the Ark Layer 2 Protocol. It demonstrates that Ark is not just a payment rail, but a transport layer for programmable Bitcoin logic.

The project contains two distinct reference implementations:

  1. ArkSwap: A trustless atomic swap architecture where Ark VTXOs are exchanged for Bitcoin Layer 1 funds using custom Taproot HTLCs.
  2. SatoshiKoi: A stateful asset protocol where VTXOs carry unique metadata (DNA). It demonstrates Client-Side Validation and Cryptographic Asset Binding to enable non-fungible assets on Bitcoin L2.

Both projects run within a controlled Regtest environment using a custom-built Ark Service Provider (ASP).

πŸ“– User Stories

To understand the utility of these protocols, we follow two users interacting with the same underlying ledger.

1. The Sovereign Exit (ArkSwap)

Meet Elena, a freelancer who gets paid in Bitcoin via Ark (Layer 2) for speed and privacy. She wants to move her savings to a Hardware Wallet (Layer 1) without using a centralized exchange (KYC).

  • The Problem: On-chain payments are expensive and slow. Lightning requires liveness and channel management.
  • The Solution: Elena accumulates 4 weekly paychecks (VTXOs) and uses ArkSwap to batch them into a single L1 transaction.
  • The Security: She sends her funds to a Smart Contract (HTLC). If the Market Maker pays her on L1, they get the VTXOs. If they fail to pay, the contract unlocks, and she reclaims her funds via the "Refund" button.

2. The Piggy Bank Collectible (SatoshiKoi)

Meet Kenji, a collector who wants to play a game on Bitcoin without paying $10 in mining fees for every move.

  • The Concept: Kenji mints a "SatoshiKoi." This isn't just a JPEG link; the Fish IS the VTXO.
  • Game Theory: To breed a rare fish, Kenji must "burn" two parent VTXOs to create a child. That child inherits not just DNA from its parents, but also the value of the minting fee. A gen 0 fish minted for 1000 satoshis contains the satoshis within itself. A gen 1 fish, then, can be redeemed for 2000 satoshis. A gen 2 fish for 4000 and so on...
  • The Value: If Kenji gets bored, he can "Smash the Piggy Bank." He performs a Unilateral Exit to Layer 1. The art (metadata) is lost, but the 1,000 sats (or more if it is a greater generation) stored inside the fish are returned to his Bitcoin wallet.

🚧 In Progress: ArkWatch (Protocol Auditor)

We are currently building ArkWatch, a dedicated block explorer and scoring engine for Ark Service Providers (ASPs).

While ArkSwap demonstrates the Application Layer (Building on Ark), ArkWatch targets the Infrastructure Layer (Verifying Ark). It proves that Ark's trustless nature is not just a theoretical claim, but an auditible fact visible on the Bitcoin blockchain.

The Research Scope:

  • Chain Indexing: Building a custom indexer to scan Bitcoin Regtest for ASP footprint (Round Transactions and Pool UTXOs).
  • Solvency Analysis: Tracking Total Value Locked (TVL) versus Unilateral Exit Volume to detect liquidity crunches or bank runs in real-time.
  • The Scorecard: An algorithmic grading system (A-F) that quantifies the safety, reliability, and efficiency of an ASP based purely on public chain data.

🧠 Technical Deep Dive: Under the Hood

This repo implements complex Bitcoin cryptography from scratch to achieve these features.

1. The "Smart Contract" Factory (ArkSwap)

File: packages/protocol/src/script.ts

  • The Mechanics: We utilize a NUMS (Nothing Up My Sleeve) Point as the internal key for our Taproot address. This cryptographically disables the default key-spending path, forcing funds to be spent only via specific script paths (Claim via Preimage or Refund via Timelock).

2. The Double Tweak (SatoshiKoi)

File: apps/web/lib/ark-client.ts

  • The Mechanics: Standard Ark VTXOs use a single tweak (Pubkey + TapTweak). For Assets, we implemented a Double Tweak (Pubkey + AssetHash + TapTweak).
  • The Result: The VTXO's address is mathematically bound to its DNA. You cannot change the asset data without changing the address, effectively making the asset immutable. The Client performs manual Elliptic Curve addition to derive the correct signing keys for these complex assets.

3. Client-Side Validation (Game Logic)

File: apps/web/lib/ark-client.ts (verifyGenetics)

  • The Mechanics: The ASP (Server) runs the breeding algorithm, but the Client does not trust it. When a new Fish arrives, the Client locally re-runs the genetic math (mixGenomes). If the ASP's result deviates even by a single bit from the protocol rules, the Client rejects the asset.

4. The Protocol Validator (ASP)

File: apps/asp/src/transfer/transfer.service.ts

  • The Mechanics: The ASP acts as the consensus layer. It extracts the raw 32-byte Public Key from the Bech32m address and performs cryptographic verification of Schnorr signatures. It enforces the rules of the network, ensuring no user can double-spend a VTXO.

🧩 Architecture Status: Real vs. Simulation

ArkSwap is designed as a Research Prototype. The codebase executes valid Bitcoin cryptographic primitives, but abstracts the expensive network settlement layers for development speed.

Component Status Description
Cryptography βœ… Native Raw Schnorr Signatures, BIP-86 Key Tweaking, and Taproot Address derivation are fully implemented.
Smart Contracts βœ… Native Actual Bitcoin Script (HTLCs) compiled into Taproot Merkle Trees.
Blockchain βœ… Native Runs a genuine Bitcoin Core node (Regtest).
Market Maker ⚠️ Hybrid Real trading logic funded with Regtest Bitcoin.
ASP (Network) ⚠️ Hybrid Validates inputs cryptographically, but "mocks" the final L1 Broadcast of the Round Transaction.
Onboarding ❌ Mocked L1 -> L2 deposits are triggered via API for instant feedback.

πŸ›  Tech Stack

  • Apps: Next.js (Wallet/UI), NestJS (ASP/Market Maker).
  • Libs: @bitcoinerlab/secp256k1 (ECC), bitcoinjs-lib (Transactions), Zod (Validation), TanStack Query (State).
  • Infra: Docker, Postgres, Redis, Playwright.

πŸš€ Getting Started

Prerequisites

  • Node.js (v18+) & pnpm
  • Docker Desktop

1. Installation

git clone https://github.com/jgmcalpine/arkswap.git
cd arkswap
pnpm install

2. Start the Infrastructure (The Universe)

Spin up the local Bitcoin Regtest node and Ark Service Provider (ASP).

cd docker
docker-compose up -d --build

3. Run the Development Servers

Start the Frontend (localhost:3000) and Backend (localhost:3001).

# From the root directory
# Note: Excludes the ASP since it runs in Docker
pnpm dev --filter=!@arkswap/asp

4. "God Mode" (Funding & Simulation)

Since this runs on Regtest, you control the blockchain. We provide scripts to mine blocks and fund wallets.

Check Blockchain Status:

./scripts/get-info.sh

Mine Blocks (Time Travel):

# Mines 101 blocks to mature coinbase rewards
./scripts/mine.sh 101

Fund the Market Maker:

# Sends 50 BTC to the Backend API wallet
curl -X POST http://localhost:3001/faucet/maker

5. Try out the app

Visit localhost:3000 and you will see the frontend for the app.

Happy Swap Path: Connect Wallet --> Deposit --> Set amount to swap --> Request Quote --> Enter L1 Address (docker exec -it bitcoind bitcoin-cli -regtest -rpcuser=ark -rpcpassword=ark getnewaddress) --> Confirm Swap --> Boom! Trustless swapping from L2 back to L1.

Something Went Wrong Swap Path: Connect Wallet --> Deposit --> Set amount to swap --> Check 'Simulate Backend Crash' --> Request Quote --> Enter L1 Address --> Confirm Swap --> Move blockchain forward 24 blocks (./scripts/mine.sh 24) --> Claim Refund --> Boom! Even if the Market Maker disappears, your funds are yours.

Mint a few SatoshiKoi and breed them: Check the specific attributes of a SatoshiKoi and notice the DNA is verified, this is client-side validation in action!

πŸ€– AI-Augmented Development

This repository was built using an AI-First workflow. The architecture, prompts, and debugging strategies were human-directed, while the boilerplate code and cryptographic implementations were generated via LLMs and rigorously audited via E2E testing.

🀝 Contributing

We welcome contributions! Please note that this project deals with financial cryptography, so we enforce strict quality controls.

This repository contains Research Code. It is not intended for deployment. Pull Requests that attempt to remove Regtest constraints or add Mainnet configuration support will be closed immediately.

Development Workflow

  1. Strict Types: We use TypeScript strict mode. No any casts are allowed.
  2. Shared Logic: All cryptographic logic belongs in packages/protocol, not in the apps.

Verification (Running Tests)

Before pushing code, please run the following suites to ensure CI will pass.

1. Code Quality (Fast) Runs linter, strict type checking, and protocol unit tests.

pnpm turbo lint
pnpm turbo type-check
pnpm --filter @arkswap/protocol test

1. End-to-End Assurance (Slow) Runs the Playwright suite against the local Docker environment.

# Ensure Docker is running first
cd docker && docker-compose up -d

# Run E2E Tests
cd ..
pnpm --filter @arkswap/web test:e2e

Project Structure

  • apps/web: Next.js Frontend (Client)
  • apps/api: NestJS Market Maker (Liquidity Provider)
  • apps/asp: NestJS Ark Service Provider (Protocol Coordinator)
  • packages/protocol: Shared Cryptography & Types

πŸ“„ License

Distributed under the MIT License. See LICENSE for more information.

About

A research prototype demonstrating programmable Ark Layer 2 transactions, using Taproot to enable trustless atomic swaps and stateful digital assets (SatoshiKoi)

Resources

License

Stars

Watchers

Forks

Packages

No packages published