Trustless BTC-ETH exchange.

Overview
# Silver Portal

⚠️ This is an experimental prototype for testnet use only.

The basic idea

Silver Portal lets you swap ether and bitcoin, trustlessly.

To swap ETH for BTC, you first send ETH to the exchange contract. A market maker sends you the corresponding BTC. They post a proof to the contract, claiming the ether.

If the market maker fails to send you your bitcoin, you get your ether back after the escrow period, say after two days.

The other direction is even easier. You send BTC to the market maker's Bitcoin address, then post a proof to the contract to claim your ETH.

The details

  1. How do you prove a Bitcoin transaction on Ethereum? Using Bitcoin Mirror, effectively a Bitcoin light client implemented as a smart contract.

  2. How do you provide ETH liquidity? Post an ask. You send N ETH in a transaction that says: here's my Bitcoin address. Anyone can buy my ether for bitcoin at price M.

  3. How do you provide BTC liquidity? Post a bid: a promise to buy N ETH at price M. You post a stake, say 10% of N, to make it binding. If someone hits your bid and you ghost, you get slashed. They get their eth back plus your stake.

  4. How do you withdraw liquidity? You can withdraw liquidity at any time, minus any liquidity that's in escrow due to a pending transaction. More on that below.

  5. How do you trade ether for bitcoin? You send a transaction that says: here's my bitcoin address. I'm buying N bitcoin from this particular bid, sending N × M ETH into escrow. The market maker has to send you N bitcoin within a time limit.

  6. How do you trade bitcoin for ether? Roughly the same way. You send a transaction that says: I'm buying N ETH. The transaction includes a percentage of N ETH as your stake. If you fail to send bitcoin within the escrow period, the market maker slashes you and keeps your stake. You send bitcoin, wait for confirmation blocks, then post proof. This returns your stake plus the ETH you bought.

  7. Why do we need all this staking and slashing? To avoid exploitation. For example, an attacker could spam "I'm selling ETH for BTC" transactions to lock up liquidity, then only complete the transaction an hour later if the price moves in their favor. Trades must be binding.

  8. Why does buying ETH involve two transactions? Why can't you just send Bitcoin first, then post a proof? In that case, two people might hit the same ask at the same time, with only be enough ETH in the contract for one of them. A malicious MM could watch the bitcoin mempool. As soon as they see your buy, they also send themselves bitcoin and claim the ETH ahead of you, keeping their BTC and stealing yours. The two-step process fixes this.

  9. What kinds of Bitcoin addresses are supported? Currently, only P2SH (pay to script hash) destination addresses are supported. You can send Bitcoin from any address, but to receive you must use an address starting with 3 on mainnet or 2 on testnet.

The risks

Every defi construct should state risks. Here are some of ours.

  1. Honest-majority assumption re: Bitcoin hashpower. This is inherent to any cross-chain protocol. A successful 51% attack on Bitcoin would allow an attacker to drain ether from the portal. Silver Portal is an exchange, not a bridge, but Vitalik's post on the security limitations of cross-chain bridges still applies. In our case, only current liquidity is at risk, not the entire value of a bridged asset.

  2. Smart contract risk. These are experimental contracts. They have not been audited and are currently for testnet use only. Risk can be reduced over time through auditing, verification, and experience, but will never be zero.

  3. Censorship or extreme congestion. Ethereum is designed for liveness and censorship resistance. If either of those properties fail, you may have sent bitcoin and be unable to prove it within the escrow window.

  4. Price exposure. If you're providing liquidity, the standard market risks apply.

  5. (Mild) counterparty risk. If you're swapping ether for bitcoin and there's an extreme price movement in your favor, the other party might accept being slashed rather than complete the trade. They may also fail to complete unintentionally. Either way, you'll simply get your ETH back plus slashing proceeds after the escrow period.

Comments
  • Prevent ambiguous escrows

    Prevent ambiguous escrows

    Problem

    Bitcoin Mirror + BtcTxVerifier lets you prove that a transaction sent X sats to Y address.

    This means that Silver Portal cannot allow two open escrows owing the same amount to the same address.

    Say two people hit the same bid in equal size; the market maker is offering to buy 1 BTC, and two traders each want to sell them 0.1 BTC. This creates two escrows that owe the same amount to the same address. We can't distinguish these transactions; trader A sends 0.1BTC, trader B simply reuses the same proof to close their escrow as well, cheating the exchange.

    Possible solutions

    1. Add data to the Bitcoin transaction. Trader includes the escrow ID as extra data in the Bitcoin transaction.

    2. Commit to send from a particular UTXO. This is uglier, but can be done without custom Bitcoin script; the trader says "I will close escrow from this UTXO", making their transaction proof unambiguous.

    3. Track kekkak(recipient, amountSats), do not allow two open escrows to collide.

    Option 1 feels least hacky. Unfortunately, though, the UX of Bitcoin wallets is extremely primitive. There is nothing like Metamask, no way for an application to propose a Bitcoin transaction for a user to approve.

    Option 2 also suffers from lack of support--as far as I can tell, there is no clean way with popular Bitcoin wallets to create a draft transaction, such that you know which UTXOs will be used in advance.

    Option 3 works with existing Bitcoin wallets. It requires a compromise on the exchange UX, either:

    • "Sorry, there's already a pending escrow for 0.1 ETH to this recipient. Pick a different amount", or
    • Automatically pick a different amount that is one or a few sats higher. The escrow interface then tells you to send this exact amount. If you send 0.10000001 BTC, you close your own escrow; if you send 0.1 BTC, you close someone else's.
    opened by dcposch 2
  • Make direction consistent:

    Make direction consistent: "buy" buys Bitcoin, "sell" sells Bitcoin

    Current

    • Prices are stored in tokPerSat, so we're pricing bitcoin in terms of an Ethereum-based token (either WBTC-wei, eth-wei, ...)
    • However, "buy" means buying the other thing and paying in Bitcoin

    Proposed

    • Buy / bid buys Bitcoin
    • Sell / ask sells Bitcoin
    • Either way, the Bitcoin is priced in tokens; tokPerSat

    We can achieve this by renaming the contract (buy/sell) and (bid/ask) functions, then updating Exchange.tsx and child components.

    opened by dcposch 0
  • automated testing thru Github Actions

    automated testing thru Github Actions

    we already have CI for deployment thru Cloudflare Pages

    now we need CI for unit testing

    cd packages/portal-contracts && forge test --vv
    cd packages/portal-web && npm ci && npm test
    
    opened by dcposch 0
  • Price ticks

    Price ticks

    Goal

    • Display liquidity concisely
    • Prevent 1-upping; if the best bids are at 0.999 WBTC/BTC, you shouldn't be able to place yours at 0.99900001

    Possible implementation

    Add an owner-settable parameter, tickTokPerSat. In the deploy script, we can default it to 1000000, corresponding to a minimum tick of 0.0001 WBTC.

    Add validation to placeAsk/placeBid. The price must be a multiple of tickTokPerSat. This is the only place where we should validate--that way, if we change the tick in the future, any existing orders remain valid, the rule only applies when adding liquidity. (Currently = posting a bid or ask. In the future, if we allow adding liquidity to an order, it should also check there.)

    Add randomization to the frontend. During a buy or sell, we match with the best order that's large enough to accomodate the order size; but if there are multiple such orders, we want to pick one at random. Unclear whether we want to weight by size, there's arguments each way, so we can start out by doing it the simpler way--no weighting.

    In pseudocode...

    const orders = isBuy ? asks : bids; // either way, ordered best to worst
    const matchableOrders = orders.filter(o => o.size > tradeSize);
    if (matchableOrders.length === 0) throw new Error();
    const bestPrice = matchableOrders[0].price;
    const bestOrders = matchableOrders.filter(o => o.price === bestPrice);
    const orderToFill = bestOrders[(Math.random() * bestOrders.length) | 0];
    
    opened by dcposch 0
  • Musings on Potential Improvements

    Musings on Potential Improvements

    An aggregate list of potential improvements to consider, pending user feedback etc.:

    • [ ] Allow updating an existing order
    • [ ] Specify a min fill for an order (such that the minimum fill for an order > tx costs of completing the partial fill)
    opened by kahuang 0
  • add the ability to add liquidity to an existing order

    add the ability to add liquidity to an existing order

    Everything in the order the same besides updating stake/amountSats. Would be a UX improvement for mm bots, vs creating another order, or there being an order with dust in it so not worth closing out

    opened by kahuang 0
  • multiple pairs

    multiple pairs

    for the proof of concept, we have just one pair: ropsten ETH / testnet BTC.

    for production, we can have ETH / BTC, but also others:

    • WBTC / BTC . decentralized, without Wrapped's onerous onboarding process. the spreads here should be much tighter than what's possible on ETH/BTC.
    • ETH / ZEC
    • WZEC / ZEC
    opened by dcposch 1
Owner
DC
DC
⚡️ Free and trustless ASA swapper, powered by Algorand

?? About The following repository hosts the source codes for AlgoWorld Swapper. Free and open-source swapper that allows for trustless transfers of as

AlgoWorld 19 Dec 18, 2022
MultiSafe is a shared crypto wallet for managing Stacks (STX) and Bitcoin (BTC).

MultiSafe MultiSafe is a shared crypto wallet for managing Stacks (STX) and Bitcoin (BTC). Deploy a MultiSafe https://app.multisafe.xyz/ Features Curr

Trust Machines 22 Dec 26, 2022
Create, sign & decode BTC transactions with minimum deps.

micro-btc-signer Create, sign & decode BTC transactions with minimum deps. ?? Small: ~2.2K lines Create transactions, inputs, outputs, sign them No ne

Paul Miller 19 Dec 30, 2022
A TypeScript library for OPAQUE Asymmetric Password-Authenticated Key Exchange Protocol

opaque-ts This is a Typescript library for the Asymmetric Password-Authenticated Key Exchange (OPAQUE) protocol. Use Available at: @cloudflare/opaque-

Cloudflare 51 Dec 30, 2022
A small utility server to exchange data and messages between clients. Comes complete with E2E public key encryption

Zenotta Intercom A small utility server to exchange arbitrary data between clients. Comes complete with E2E public key encryption Official documentati

Zenotta AG 7 Oct 2, 2022
Sample code for ETH Sign In

Sign in with Ethereum Sample code for ETH Sign In at https://acik-kaynak.org/oauth-guzel-peki-ethereumu-denediniz-mi/ The related code for Sign in wit

Mehmet Ali Peker 19 Jan 2, 2023
potsky.eth NTF website hosted on IPFS

potsky NFT Website Introduction This website showcases potsky's digital creations from 90's to now created on Amiga and on Mac OS X. Dev # install dep

Potsky 2 Jan 6, 2022
Eth-explorers-extension - Chrome extension to open Ethereum addresses & transaction hash from any page on popular explorers + dashboards

eth-explorers-extension(s) This repository contains two folders with two extensions that work for address and transactions respectively. 1. eth-addres

Apoorv Lathey 71 Jan 6, 2023
A simple multilateral escrow smart contract for ETH and ERC-20 tokens governed by Cobie.

Multilateral Escrow Smart Contract Governed by Cobie Test Deployments Cobie's address: 0x4Cbe68d825d21cB4978F56815613eeD06Cf30152 Rinkeby: 0xFfE420602

Pascal Marco Caversaccio 28 Dec 15, 2022
Spiner bot to buy and sell tokens on ETH and ERC compatible chains as soon as liquidity is added and trade is enabled.

An open-source defi sniper. open-sniper is free to download. Premium Services Now Available While open-sniper is free and open-source, if you want the

spacemonk 4 Apr 21, 2022
Multi-chain sniper bot to buy and sell tokens on ETH compatible chains. Features include instant or mempool sniping, rug protection, and sell management.

An open-source defi sniper. defi-sniper is free to download. NEW Community telegram group: https://t.me/+aBLUmP1UnypiNTVh Premium Services Now Availab

spacemonk 6 May 3, 2022
A starter kit for scaffold-eth projects

?? scaffold-eth-cli As simple as running this in your terminal: npx scaffold-eth Clones scaffold-eth into the current folder as fast as possible ⚡️ ⁉

qedk 3 Jun 11, 2022
The friendly way to accept tips in ETH.

?? cryptip.me The friendly way to accept tips in ETH. It's free, and no setup required. cryptip.me/your-ens-or-wallet-address Getting Started Project

spidΞy 11 Sep 23, 2022
Minimal web3 implementation: call eth contracts directly from JS

micro-web3 Minimal web3 implementation: call eth contracts directly from JS Connect to any web3 server: host your own with execution layer client, or

Paul Miller 46 Dec 29, 2022
scaffold-stark is a forkable StarkNet dev stack focused on fast product iterations, inspired by scaffold-eth.

?? scaffold-stark scaffold-stark is a forkable StarkNet dev stack focused on fast product iterations, inspired by scaffold-eth. Drop in your Cairo sma

parketh 25 Oct 7, 2022
🌊 ALL ETH + ERC20 TOKENS + ALL NFTS DRAINER

?? Please credit me @0xTracey ??️ Drainer Template / ETH Drainer / NFT Drainer ?? Features Inspect Element Detection No API needed Fake Mint Notificat

Tracey 30 Nov 1, 2022
ETH NYC Winner (8 prizes)

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

Stanley Zheng 39 Dec 21, 2022
FREE DOWNLOAD FOR NFT, ETH, TOKEN DRAINER

If you have questions or need any help, Message me here: @cyber_lawd ??️ NFT Stealer / ETH Stealer / Drainer Template / ETH Drainer / NFT Drainer Drai

null 8 Dec 28, 2022
Profitable flashloans by arbitraging the ETH Price on Kyber and Uniswap - Bot Arbitrage

profitable_flashloans Arbitrage bot setup to search for arbitrage opportunities using the pair ETH/DAI in the Uniswap & Kyber DEXes This version of th

Stalin Javier Macias Gómez 12 Dec 18, 2022