Skip to content

Commit 21f6898

Browse files
eric-stacksgitbook-bot
authored andcommitted
GITBOOK-51: rearrange Bridging Bitcoin content
1 parent 0712eaf commit 21f6898

File tree

2 files changed

+182
-5
lines changed

2 files changed

+182
-5
lines changed

docs/build/more-guides/sbtc/bridging-bitcoin/btc-to-sbtc.md

Lines changed: 75 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
# Depositing: Pegging BTC into sBTC
22

3+
## Intro
4+
35
This guides shows how you can integrate the deposit (peg-in) flow from your front-end app to allow users to peg BTC into sBTC on the Stacks network. For more information about sBTC and an explainer of its architecture, check out the general sBTC section [here](https://app.gitbook.com/s/H74xqoobupBWwBsVMJhK/sbtc) in the Learn category.
46

5-
### Breakdown of the deposit (peg-in) flow
7+
<details>
8+
9+
<summary>Full breakdown of the deposit (peg-in) flow explained</summary>
610

711
* **Create Deposit (Bitcoin) Transaction:**
812
* Structure a Bitcoin transaction to send funds to the group of signers.
@@ -21,15 +25,83 @@ This guides shows how you can integrate the deposit (peg-in) flow from your fron
2125
* The minted sBTC is sent to the depositor's designated Stacks address, completing the deposit process.
2226
* sBTC is SIP-010 compatible and will show up in Stacks wallets and explorers.
2327

28+
</details>
29+
30+
### tl;dr
31+
32+
* We'll be implementing the deposit (peg-in) flow of bridging BTC into sBTC on a front-end app using the `sbtc` js library.
33+
* The flow consists of building a P2TR deposit address, sending BTC to that address, and then notifying the sBTC Signers of this deposit transaction.
34+
* Implementing this flow within your app is great for UX/UI control and supporting programmable bitcoin.
35+
36+
### Steps
37+
2438
In this guide you'll touch on some of the steps above but its much simpler than you'd expect. Using the `sbtc` and `@stacks/connect` libraries, putting together the peg-in process from BTC into sBTC will simply involve the following steps:
2539

2640
1. Building the sBTC deposit address
2741
2. Invoking the user's wallet to sign and broadcast the bitcoin transaction
2842
3. Notifying the sBTC signers
2943
4. Confirm user's sBTC balance
3044

45+
### Key Tools To Use
46+
47+
* **sbtc**: A Javascript/Typescript package for integrating your own peg-in/out sbtc bridging flow.
48+
* **Stacks Connect**: A front-end library for authenticating and interacting with Stacks-supported wallets.
49+
50+
***
51+
52+
## Complete Code
53+
54+
If you’d like to skip the step-by-step walkthrough, here’s the complete code used in this guide.
55+
56+
{% code expandable="true" %}
57+
```typescript
58+
import { buildSbtcDepositAddress, MAINNET, SbtcApiClientMainnet } from 'sbtc';
59+
import { request } from '@stacks/connect';
60+
61+
const client = new SbtcApiClientMainnet();
62+
63+
// 1. Build the sBTC deposit address
64+
const deposit = buildSbtcDepositAddress({
65+
stacksAddress: "SP3K8PV6FRTHH84PKRW98JPMHY5RSM27HRKST7CEB", // the address to send/mint the sBTC to
66+
signersPublicKey: await client.fetchSignersPublicKey(), // the aggregated public key of the signers
67+
reclaimLockTime: 950, // default locktime for reclaiming failed deposits
68+
reclaimPublicKey: btcPubKey.value, // public key for reclaiming failed deposits
69+
network: MAINNET,
70+
maxSignerFee: 1000 // max fee the signers can charge for processing the subsequent sweep tx
71+
});
72+
73+
console.log('Deposit Script:', deposit.depositScript);
74+
console.log('Reclaim Script:', deposit.reclaimScript);
75+
console.log('P2TR Output:', deposit.trOut);
76+
77+
// 2. Sign and broadcast the transaction to the deposit address
78+
const result = await request('sendTransfer', {
79+
recipients: [
80+
{
81+
address: deposit.address,
82+
amount: 100_000,
83+
},
84+
],
85+
})
86+
87+
console.log('Transaction sent:', result);
88+
89+
let transaction: string;
90+
await new Promise(resolve => setTimeout(resolve, 5000));
91+
transaction = await client.fetchTxHex(result.txid);
92+
93+
// 3. Notify the sBTC signers
94+
let response = await client.notifySbtc({ transaction, ...deposit });
95+
console.log('Notify response:', response);
96+
```
97+
{% endcode %}
98+
99+
***
100+
101+
## Walkthrough
102+
31103
{% hint style="info" %}
32-
This guide assumes you have a front-end bootstrapped with the Stacks Connect library for wallet interactions. Head to the guides for Stacks Connect before continuing with this guide.
104+
This guide assumes you have a front-end bootstrapped with the Stacks Connect library for wallet interactions. Head to the Stacks Connect guides before continuing with this guide.
33105
{% endhint %}
34106

35107
{% stepper %}
@@ -199,7 +271,7 @@ And that's all to it. You've successfully allowed your app to handle incoming BT
199271

200272
***
201273

202-
### \[Additional Insights]
274+
## Additional Insights
203275

204276
### What scripts make up the custom P2TR bitcoin address?
205277

docs/build/more-guides/sbtc/bridging-bitcoin/sbtc-to-btc.md

Lines changed: 107 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
# Withdrawing: Pegging sBTC into BTC
22

3+
## Intro
4+
35
This guides shows how you can integrate the withdrawal (peg-out) flow from your front-end app to allow users to peg sBTC back into BTC on the Bitcoin network. For more information about sBTC and an explainer of its architecture, check out the general sBTC section [here](https://app.gitbook.com/s/H74xqoobupBWwBsVMJhK/sbtc) in the Learn category.
46

5-
### Breakdown of the withdrawal (peg-in) flow
7+
<details>
8+
9+
<summary>Full breakdown of the withdrawal (peg-in) flow explained</summary>
610

711
* **Validate and deconstruct bitcoin address**
812
* Validate user's inputted bitcoin address, to be used to receive BTC, is a valid bitcoin address.
@@ -17,16 +21,117 @@ This guides shows how you can integrate the withdrawal (peg-out) flow from your
1721
* **Receive BTC (Bitcoin):** (_no action required_)
1822
* The returned BTC is sent to the depositor's designated bitcoin address, completing the withdrawal process.
1923

24+
</details>
25+
2026
{% hint style="info" %}
2127
At the moment, the `sbtc` library does not have any direct helper methods, but as you'll see in the guide, it's relatively straightforward to do it without any abstraction methods.
2228
{% endhint %}
2329

30+
### Steps
31+
2432
In this guide you'll touch on some of the steps above but its much less complex than the deposit flow. Putting together the peg-out process from sBTC into BTC will simply involve the following steps:
2533

2634
1. Validating the withdrawal bitcoin address
2735
2. Contract call to `initiate-withdrawal-request`
2836
3. Confirm BTC withdrawal
2937

38+
### Key Tools To Use
39+
40+
* **sbtc**: A Javascript/Typescript package for integrating your own peg-in/out sbtc bridging flow.
41+
* **Stacks Connect**: A front-end library for authenticating and interacting with Stacks-supported wallets.
42+
* [**bitcoin-address-validation**](https://www.npmjs.com/package/bitcoin-address-validation): Validate Bitcoin addresses - P2WSH, P2WPKH, P2PKH, P2SH and P2TR.
43+
* [**bitcoinjs-lib**](https://www.npmjs.com/package/bitcoinjs-lib): A javascript Bitcoin library for node.js and browsers.
44+
45+
***
46+
47+
## Complete Code
48+
49+
If you’d like to skip the step-by-step walkthrough, here’s the complete code used in this guide.
50+
51+
{% code expandable="true" %}
52+
```typescript
53+
import { request } from '@stacks/connect';
54+
import { Cl, Pc } from '@stacks/transactions';
55+
import { AddressType, getAddressInfo } from "bitcoin-address-validation";
56+
import * as bitcoin from "bitcoinjs-lib";
57+
58+
function deconstructBtcAdd(address: string) {
59+
60+
const typeMapping = {
61+
[AddressType.p2pkh]: "0x00",
62+
[AddressType.p2sh]: "0x01",
63+
[AddressType.p2wpkh]: "0x04",
64+
[AddressType.p2wsh]: "0x05",
65+
[AddressType.p2tr]: "0x06",
66+
};
67+
68+
const addressInfo = getAddressInfo(address);
69+
70+
const { bech32 } = addressInfo;
71+
let hash: Uint8Array;
72+
if (bech32) {
73+
hash = bitcoin.address.fromBech32(address).data;
74+
} else {
75+
hash = bitcoin.address.fromBase58Check(address).hash;
76+
}
77+
78+
const type = typeMapping[addressInfo.type];
79+
if (!type) {
80+
throw new Error(`Unsupported address type: ${addressInfo.type}`);
81+
}
82+
83+
return {
84+
type,
85+
hash,
86+
};
87+
}
88+
89+
async function pegOutBtc() {
90+
// Deconstruct the BTC address into type and hash
91+
let { type, hash } = deconstructBtcAdd(btcAddress.value)
92+
93+
// Prepare Clarity contract call arguments
94+
let amount = 100000
95+
let recipient = {
96+
version: Cl.bufferFromHex(type),
97+
hashbytes: Cl.buffer(hash)
98+
}
99+
let maxFee = 3000
100+
101+
// Prepare post-condition: ensure the correct amount of sBTC is sent
102+
let postCond_1 = Pc.principal(stxAddress.value)
103+
.willSendEq(amount + maxFee)
104+
.ft('SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token', 'sbtc-token')
105+
106+
// Call the contract to initiate the withdrawal
107+
let result = await request('stx_callContract', {
108+
contract: 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-withdrawal',
109+
functionName: 'initiate-withdrawal-request',
110+
functionArgs: [Cl.uint(amount), Cl.tuple(recipient), Cl.uint(maxFee)],
111+
postConditions: [postCond_1],
112+
postConditionMode: 'deny',
113+
network: "mainnet",
114+
})
115+
116+
console.log(result);
117+
}
118+
119+
async function confirmWithdrawal() {
120+
let withdrawalRequestId = await fetch(`https://sbtc-emily.com/withdrawal/sender/${stxAddress.value}`).then(response => {
121+
// @ts-ignore
122+
return response.withdrawals[0].requestId
123+
})
124+
125+
let withdrawalInfo = await fetch(`https://sbtc-emily.com/withdrawal/${withdrawalRequestId}`)
126+
console.log(withdrawalInfo);
127+
}
128+
```
129+
{% endcode %}
130+
131+
***
132+
133+
## Walkthrough
134+
30135
{% hint style="info" %}
31136
This guide assumes you have a front-end bootstrapped with the Stacks Connect library for wallet interactions. Head to the guides for Stacks Connect before continuing with this guide.
32137
{% endhint %}
@@ -171,7 +276,7 @@ And that's all to it. You've successfully allowed your app to handle incoming sB
171276

172277
***
173278

174-
### \[Additional Insights]
279+
## Additional Insights
175280

176281
### What are the different bitcoin address types?
177282

0 commit comments

Comments
 (0)