Skip to content

Commit a10104e

Browse files
authored
add TypeScript SDK page & improve other pages (#383)
1 parent acae9f2 commit a10104e

File tree

15 files changed

+203
-36
lines changed

15 files changed

+203
-36
lines changed

website/docs/basics/about-bch.md

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,14 @@ Bitcoin Cash (ticker BCH) is one of the biggest cryptocurrencies. Bitcoin Cash i
88
Bitcoin Cash shares many of the same fundamentals as Bitcoin (BTC) like the *Proof-of-Work* consensus algorithm and the *UTXO data-model*. However regarding smart contract programmability, Bitcoin Cash has significantly diverged from Bitcoin (BTC). We will go over the main differences between BCH and BTC, and then delve into the smart contract capabilities of Bitcoin Cash!
99

1010
:::info
11-
To learn more about the Bitcoin Basics refer to the book ['Mastering Bitcoin'](https://github.com/bitcoinbook/bitcoinbook). The core of Bitcoin's design is still very much the same in Bitcoin Cash. To learn more about BCH's transaction lifecycle, see the dedicated guide ['Transaction Lifecycle'](/docs/guides/lifecycle).
11+
To learn more about the Bitcoin Basics refer to the book ['Mastering Bitcoin'][Mastering Bitcoin]. The core of Bitcoin's design is still very much the same in Bitcoin Cash. To learn more about BCH's transaction lifecycle, see the dedicated guide ['Transaction Lifecycle'](/docs/guides/lifecycle).
1212
:::
1313

1414
## How BCH differs from BTC
1515

1616
Although BCH and BTC share the same Bitcoin fundamentals, both projects have significantly diverged in some areas since 2017. For example, Bitcoin Cash does not have Segwit or Taproot, instead Bitcoin Cash has had multiple upgrades specifically focused on improving the smart contract capabilities. Bitcoin Cash has re-enabled many useful opcodes, has introduce native introspection, has added CashTokens, has reworked the script limits and introduced BigInts.
1717

18-
So part that **has** significantly diverged between BTC and BCH is the *virtual machine* (VM), the environment in which smart contracts are evaluated. So the greatly improved VM specifically is what makes it possible to write powerful smart contracts on BCH in the first place!
18+
So part that **has** significantly diverged between BTC and BCH is the *virtual machine* (VM), the environment in which smart contracts are evaluated. The Bitcoin Cash VM is also referred to as the **CashVM**. The greatly improved VM specifically is what makes it possible to write powerful smart contracts on BCH in the first place! On the overview of [all the BCH network upgrades][BCH upgrades], you'll notice the recent years have been fully focused on VM improvements.
1919

2020
## UTXO model
2121
Bitcoin Cash transactions work with in- and outputs. All current balances are so called *Unspent Transaction Outputs (UTXOs)*, which simply means they can be used as inputs for future spending transactions.
@@ -39,7 +39,7 @@ Bitcoin Cash has had many script upgrades, including transaction introspection a
3939
Smart contracts on Bitcoin Cash only have access to the current transaction context, which enables 'local state'. This model allows transactions to be verified independently and efficiently. Because there is no global state that can impact the execution of these smart contracts, the results are deterministic and predictable.
4040

4141
:::tip
42-
The UTXO model where transactions only have access to the local transaction context enables parallel transaction validation and is the reason why Bitcoin Cash is hugely scalable!
42+
The UTXO model where transactions only have access to the local transaction context enables parallel transaction validation and is the reason why Bitcoin Cash is hugely scalable with low fees!
4343
:::
4444

4545
### Bitcoin Cash Script
@@ -48,10 +48,13 @@ The locking and unlocking scripts of regular transactions and smart contracts on
4848

4949
### CashScript
5050

51-
CashScript is a high-level programming language for smart contracts on Bitcoin Cash that offers a strong abstraction for a smoother development experience. CashScript fully abstracts the management of items on the 'stack' from developers, allowing them to focus on their application logic instead of low-level details.
51+
CashScript is a high-level programming language for smart contracts on Bitcoin Cash that offers a strong abstraction for a smoother development experience. CashScript fully abstracts the management of items on the 'stack' from contract developers, allowing them to focus on their application logic instead of low-level details.
5252

5353
The CashScript syntax is based on Ethereum's smart contract language Solidity, but its functionality is very different since smart contracts on Bitcoin Cash differ greatly from smart contracts on Ethereum.
5454

5555
:::info
56-
Bitcoin's "Local State" versus Ethereum's "Global State" requires a very different mental model and way to structure smart contract applications!
56+
Bitcoin Cash's "Local State" versus Ethereum's "Global State" requires a very different mental model and way to structure smart contract applications!
5757
:::
58+
59+
[Mastering Bitcoin]: https://github.com/bitcoinbook/bitcoinbook
60+
[BCH upgrades]: https://upgradespecs.bitcoincashnode.org/

website/docs/compiler/compiler.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ title: Compiler
55
The CashScript compiler is called `cashc` and is used to compile CashScript `.cash` contract files into `.json` (or `.ts`) artifact files.
66
These artifact files can be used to instantiate a CashScript contract with the help of the CashScript SDK. For more information on this artifact format refer to [Artifacts](/docs/compiler/artifacts).
77

8+
:::info
9+
Because of the separation of the compiler and the SDK, CashScript contracts can be integrated into other programming languages in the future.
10+
:::
11+
812
## Command Line Interface
913

1014
The `cashc` command line interface is used to compile CashScript `.cash` files into `.json` (or `.ts`) artifact files.

website/docs/guides/covenants.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ Covenants can also use 'simulated state', where state is kept in the contract sc
147147

148148
To demonstrate the concept of 'local state' we consider the Mecenas contract again, and focus on a drawback of this contract: you have to claim the funds at exactly the right moment or you're leaving money on the table. Every time you claim money from the contract, the `this.age` counter is reset, so the next claim is possible 30 days after the previous claim. So if we wait a few days to claim, **these days are basically wasted**.
149149

150-
Besides these wasted days it can also be inconvenient to claim at set intervals, rather than the "streaming" model that the Ethereum project [Sablier](https://www.sablier.finance/) employs. Instead of set intervals, you should be able to claim funds at any time during the "money stream". Using local state, we can approach a similar system with BCH.
150+
Besides these wasted days it can also be inconvenient to claim at set intervals, rather than the "streaming" model that the Ethereum project [Sablier][Sablier] employs. Instead of set intervals, you should be able to claim funds at any time during the "money stream". Using local state, we can approach a similar system with BCH.
151151

152152
```solidity
153153
// Mutable NFT Commitment contract state
@@ -328,3 +328,4 @@ We have discussed the main uses for covenants as they exist on Bitcoin Cash toda
328328
Keeping local state in NFTs and issuing NFTs as receipts are two strategies which can be used to create much more sophisticated decentralized applications. You can read more of these advanced CashTokens use cases in our [dedicated guide](/docs/guides/cashtokens#cashtokens-use-cases)!
329329

330330
[bitcoin-covenants]: https://fc16.ifca.ai/bitcoin/papers/MES16.pdf
331+
[Sablier]: https://www.sablier.finance/

website/docs/guides/lifecycle.md

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ The "first-seen rule" is a default mempool inclusion and relay rule for full nod
3737
On BTC the mempool node default policy got changed to replace-by-fee, and tooling to submit your non-standard transaction directly to mining pools has become commonplace with ordinals.
3838
:::
3939

40-
The first-seen rule is subjective based on time, because of this different parts of the network might enforce this rule for conflicting transactions in case of a race condition. For P2PKH transactions a trustless notification system was developed called [double-spend-proofs](https://docs.bitcoincashnode.org/doc/dsproof-implementation-notes/) (DSPs). However DSPs unfortunately do not work for smart contract transactions.
40+
The first-seen rule is subjective based on time, because of this different parts of the network might enforce this rule for conflicting transactions in case of a race condition. For P2PKH transactions a trustless notification system was developed called [double-spend-proofs][double-spend-proofs] (DSPs). However DSPs unfortunately do not work for smart contract transactions.
4141

4242
## Unconfirmed Transaction Chains
4343

@@ -81,7 +81,7 @@ A "Chain Reorganization" or reorg for short is when the full nodes discard the c
8181

8282

8383
:::tip
84-
A great resource to learn more details about reorgs is the ['Chain Reorganization'](https://learnmeabitcoin.com/technical/blockchain/chain-reorganization/) page on the info website learn-me-a-bitcoin.
84+
A great resource to learn more details about reorgs is the ['Chain Reorganization'][chain-reorganization] page on the info website learn-me-a-bitcoin.
8585
:::
8686

8787
:::note
@@ -90,3 +90,6 @@ Many exchanges however use a 6-block confirmation policy for Bitcoin Cash deposi
9090
:::
9191

9292
Chain reorgs don't always include all the same transactions, so some transactions can get un-included from the blockchain with a reorg. In this scenario, if no competing transaction was mined then the un-included transaction will just return to the mempool waiting for inclusion in a next block.
93+
94+
[double-spend-proofs]: https://docs.bitcoincashnode.org/doc/dsproof-implementation-notes/
95+
[chain-reorganization]: https://learnmeabitcoin.com/technical/blockchain/chain-reorganization/

website/docs/guides/optimization.md

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -139,25 +139,29 @@ contract Example(){
139139

140140
In Cashscript, when defining multiple functions, a `selectorIndex` parameter is added under-the-hood to select which of the contract's functions you want to use, this wraps your functions in big `if-else` cases. However when combining multiple functions in one cases you will have to think about the function conditions and `if-else` branching yourself.
141141

142-
## Hand-optimizing Bytecode
142+
## Advanced: Hand-optimizing Bytecode
143+
144+
You can still use the CashScript TypeScript SDK while using a hand-optimized or hand-written contract, although this is considered advanced functionality.
145+
146+
There's two ways to go about this, either you create a custom `Artifact` so you can still use the `Contract` class or you create a custom `Unlocker` to use in the transaction building directly.
147+
148+
### Note on Premature Optimizations
143149

144150
It's worth considering whether hand-optimizing the contract is necessary at all. If the contract works and there is no glaring inefficiency in the bytecode, perhaps the best optimization is to not to obsess prematurely about the transaction size with Bitcoin Cash's negligible fees.
145151

146152
>We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.
147153
148154
### Optimizing with the BitauthIDE
149155

150-
When optimizing the bytecode of your contract to ensure it is the smallest possible bytesize you'll likely want to use the [BitauthIDE](https://ide.bitauth.com) so you can see the stack changes for each executed OpCode. Low-level understanding can also give good intuition about the [optimization tips](#optimization-tips) for the CashScript code.
156+
When optimizing the bytecode of your contract to ensure it is the smallest possible bytesize you'll likely want to use the [BitauthIDE][BitauthIDE] so you can see the stack changes for each executed OpCode. Low-level understanding can also give good intuition about the [optimization tips](#optimization-tips) for the CashScript code.
151157

152-
### Overwriting the Artifact
158+
### Method 1) Custom Artifact
153159

154160
To manually optimize a CashScript contract's bytecode, you need to overwrite the `bytecode` key of your contract artifact.
155161

156162
If you manually overwrite the `bytecode` in the artifact, the auto generated 2-way-mapping generated by the compiler becomes obsolete. You are no longer compiling high-level CashScript code into BCH script, instead you are writing BCH script by hand.
157163
This causes the link of the BCH opcodes to your original CashScript code will be entirely lost for debugging.
158164

159-
You can still use the CashScript TypeScript SDK while using a hand-optimized or hand-written contract.
160-
161165

162166
```typescript
163167
interface Artifact {
@@ -172,7 +176,33 @@ If you use hand-optimized `bytecode` in your Contract's artifact, the `debug` in
172176
:::
173177

174178
:::tip
175-
You can create an `Artifact` for a fully hand-written contract so it becomes possible to use the contract with the nice features of the CashScript SDK! An example of this is [Cauldron_Swap_Test](https://github.com/mr-zwets/Cauldron_Swap_Test) which uses `Artifact bytecode` not produced by `cashc` at all but still uses the CashScript SDK.
179+
You can create an `Artifact` for a fully hand-written contract so it becomes possible to use the contract with the nice features of the CashScript SDK! An example of this is [Cauldron_Swap_Test][Cauldron_Swap_Test] which uses `Artifact bytecode` not produced by `cashc` at all but still uses the CashScript SDK.
176180
:::
177181

182+
### Method 2) Custom Unlockers
183+
184+
In the [addInput() method][addInput()] on the TransactionBuilder you can provide a custom `Unlocker`
185+
186+
```ts
187+
transactionBuilder.addInput(utxo: Utxo, unlocker: Unlocker, options?: InputOptions): this
188+
```
189+
190+
the `Unlocker` interface is the following:
191+
192+
```ts
193+
interface Unlocker {
194+
generateLockingBytecode: () => Uint8Array;
195+
generateUnlockingBytecode: (options: GenerateUnlockingBytecodeOptions) => Uint8Array;
196+
}
197+
198+
interface GenerateUnlockingBytecodeOptions {
199+
transaction: Transaction;
200+
sourceOutputs: LibauthOutput[];
201+
inputIndex: number;
202+
}
203+
```
204+
205+
178206
[BitauthIDE]: https://ide.bitauth.com
207+
[Cauldron_Swap_Test]: https://github.com/mr-zwets/Cauldron_Swap_Test
208+
[addInput()]: /docs/sdk/transaction-builder#addinput

website/docs/language/examples.md

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
title: Examples
33
---
44

5-
An extensive collection of examples is available in the [GitHub repository](https://github.com/CashScript/cashscript/tree/master/examples). Below we discuss a few of these examples in more details and go through their functionality. This example page focuses on the CashScript syntax, while the [SDK Examples page](/docs/sdk/examples) in the SDK section focuses on use of the SDK to build an application.
5+
An extensive collection of examples is available in the [GitHub repository][GitHub-CashScript-Examples]. Below we discuss a few of these examples in more details and go through their functionality. This example page focuses on the CashScript syntax, while the [SDK Examples page](/docs/sdk/examples) in the SDK section focuses on use of the SDK to build an application.
66

77
## HodlVault
88
For better or worse, HODLing and waiting for price increases is one of the main things people want to do with their cryptocurrency. But it can be difficult to hold on to your cryptocurrency when the price is going down. So to prevent weak hands from getting the best of you, it's better to store your stash in a smart contract that enforces HODLing for you.
@@ -90,7 +90,7 @@ contract Mecenas(bytes20 recipient, bytes20 funder, int pledge, int period) {
9090

9191
## AMM DEX
9292

93-
AMM DEX contract based on [the Cauldron DEX contract](https://www.cauldron.quest/_files/ugd/ae85be_b1dc04d2b6b94ab5a200e3d8cd197aa3.pdf), you can read more details about the contract design there.
93+
AMM DEX contract based on [the Cauldron DEX contract][Cauldron-Whitepaper], you can read more details about the contract design there.
9494

9595
The CashScript contract code has the big advantage of abstracting away any stack management, having variable names, explicit types and a logical order of operations (compared to the 'reverse Polish notation' of raw script).
9696

@@ -135,6 +135,9 @@ contract DexContract(bytes20 poolOwnerPkh) {
135135
}
136136
```
137137

138-
Compared to the manually written and hand-optimized opcodes version of the contract, the CashScript compiled bytecode has just 5 extra opcodes overhead (7 extra bytes). Furthermore, even contracts with hand-optimized bytecode can still be used with the CashScript SDK, [find out more in the optimization guide](/docs/guides/optimization#hand-optimizing-bytecode).
138+
Compared to the manually written and hand-optimized opcodes version of the contract, the CashScript compiled bytecode has just 5 extra opcodes overhead (7 extra bytes). Furthermore, even contracts with hand-optimized bytecode can still be used with the CashScript SDK, [find out more in the optimization guide](/docs/guides/optimization#advanced-hand-optimizing-bytecode).
139139

140140
More advanced examples on covenants, using NFTs to keep local state and issuing NFTs as receipts can be found in the [Covenants & Introspection Guide](/docs/guides/covenants).
141+
142+
[GitHub-CashScript-Examples]: https://github.com/CashScript/cashscript/tree/master/examples
143+
[Cauldron-Whitepaper]: https://www.cauldron.quest/_files/ugd/ae85be_b1dc04d2b6b94ab5a200e3d8cd197aa3.pdf

website/docs/releases/release-notes.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@ title: Release Notes
2424
- :hammer_and_wrench: Improve libauth template generation.
2525
- :bug: Fix bug where `SignatureTemplate` would not accept private key hex strings as a signer.
2626

27+
---
28+
29+
https://x.com/CashScriptBCH/status/1973692336782876974
30+
2731
## v0.11.5
2832

2933
#### CashScript SDK

website/docs/sdk/electrum-network-provider.md

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,17 @@
22
title: Electrum Network Provider
33
---
44

5-
The CashScript SDK needs to connect to the BCH network to perform certain operations, like retrieving the contract's balance, or sending transactions. By default the network provider is an `ElectrumNetworkProvider`.
5+
The CashScript SDK needs to connect to the BCH network to perform certain operations, like retrieving the contract's balance, or sending transactions. The recommended network provider is the `ElectrumNetworkProvider`.
66

7-
## ElectrumNetworkProvider
7+
## Creating an ElectrumNetworkProvider
88

9-
The ElectrumNetworkProvider uses [@electrum-cash/network][electrum-cash] to connect to the BCH network. Both `network` and `options` parameters are optional, and they default to mainnet with the `bch.imaginary.cash` electrum server.
9+
The ElectrumNetworkProvider uses [@electrum-cash/network][electrum-cash] library to connect to the configured electrum server. The connection uses a single, trusted electrum server so it does no have any fallback logic and does not validate SPV proofs for chain inclusion.
10+
11+
By default the `ElectrumNetworkProvider` creates a short-lived connection only when requests are pending. To configure this see the section on '[Manual Connection Management](#manual-connection-management)'.
12+
13+
### Constructor
14+
15+
Both `network` and `options` parameters are optional, and they default to `mainnet` with the `bch.imaginary.cash` electrum server.
1016

1117
```ts
1218
new ElectrumNetworkProvider(network?: Network, options?: Options)
@@ -44,6 +50,9 @@ const hostname = 'chipnet.bch.ninja';
4450
const provider = new ElectrumNetworkProvider('chipnet', { hostname });
4551
```
4652

53+
## ElectrumNetworkProvider Methods
54+
55+
4756
### getUtxos()
4857
```ts
4958
async provider.getUtxos(address: string): Promise<Utxo[]>;
@@ -143,5 +152,27 @@ provider.disconnect(): Promise<boolean>;
143152

144153
Disconnects from the electrum client, returns `true` if the client was connected, `false` if it was already disconnected.
145154

155+
## Using electrum-cash functionality
156+
157+
To use more of the electrum-specific functionality which is not exposed in the `ElectrumNetworkProvider` you can simply call the methods on the electrum Client itself.
158+
159+
### Custom Electrum Client
160+
161+
When initializing an `ElectrumNetworkProvider` you have the option in the constructor to provide a custom electrum client. This way you can use one and the same indexer server for blockchain information but use it through two different interfaces. This allows you to access all underlying functionality of the [@electrum-cash/network][electrum-cash] library like address and blockHeight subscriptions.
162+
163+
If intending to use electrum-cash subscriptions, make sure to set `manualConnectionManagement` to true, so the `ElectrumNetworkProvider` does not disconnect after each request.
164+
165+
#### example
166+
167+
```ts
168+
import { ElectrumClient } from '@electrum-cash/network';
169+
import { ElectrumNetworkProvider } from 'cashscript';
170+
171+
const electrum = new ElectrumClient('CashScript Application', '1.4.1', 'chipnet.bch.ninja');
172+
const provider = new ElectrumNetworkProvider(Network.CHIPNET, {
173+
electrum, manualConnectionManagement: true
174+
});
175+
await electrum.connect();
176+
```
146177

147178
[electrum-cash]: https://www.npmjs.com/package/@electrum-cash/network

0 commit comments

Comments
 (0)