-
TBC Components
+
Bitcoin Computer Components
A component library for smart contract driven applications
@@ -13,16 +13,17 @@
This package contains components that are used in several applications. Have a look at the other packages for how to use.
Currently it contains the following:
-* [Auth](./src/Auth.tsx) - Login and logout
-* [Wallet](./src/Wallet.tsx) - Deposit cryptocurrency
-* [Gallery](./src/Gallery.tsx) - displays a grid of smart objects
-* [SmartObject](./src/SmartObject.tsx) - displays a smart object and has a form for each of its methods
-* [Transaction](./src/Transaction.tsx) - displays a transaction including its TBC expression if it has one
-* [Modal](./src/Wallet.tsx) - displays a modal window
+
+- [Auth](./src/Auth.tsx) - Login and logout
+- [Wallet](./src/Wallet.tsx) - Deposit cryptocurrency
+- [Gallery](./src/Gallery.tsx) - displays a grid of smart objects
+- [SmartObject](./src/SmartObject.tsx) - displays a smart object and has a form for each of its methods
+- [Transaction](./src/Transaction.tsx) - displays a transaction including its Bitcoin Computer expression if it has one
+- [Modal](./src/Wallet.tsx) - displays a modal window
## Use
-To re-build the code run
+To re-build the code run
@@ -36,4 +37,4 @@ You might have to restart the applications.
## Legal Notice
-See [here](https://github.com/bitcoin-computer/monorepo/tree/main/packages/lib#legal-notice).
\ No newline at end of file
+See [here](https://github.com/bitcoin-computer/monorepo/tree/main/packages/lib#legal-notice).
diff --git a/packages/docs/.prettierrc b/packages/docs/.prettierrc
new file mode 100644
index 000000000..0e68044eb
--- /dev/null
+++ b/packages/docs/.prettierrc
@@ -0,0 +1,6 @@
+{
+ "printWidth": 100,
+ "semi": false,
+ "singleQuote": true,
+ "trailingComma": "all"
+}
diff --git a/packages/docs/Examples/chat.md b/packages/docs/Examples/chat.md
index 47a4c81c5..935306417 100644
--- a/packages/docs/Examples/chat.md
+++ b/packages/docs/Examples/chat.md
@@ -7,7 +7,7 @@ icon: comment-discussion
## Smart Contract
-A chat is just a smart object with a property `messages` of type `string[]`. Like all smart objects it has an `_owners` property set to the current data owner. The [`_readers`](./how-it-works.md#keyword-properties-control-the-transaction-being-built) property can be used to restrict read access.
+A chat is just a smart object with a property `messages` of type `string[]`. Like all smart objects it has an `_owners` property set to the current data owner. The [`_readers`](./how-it-works.md#keyword-properties-control-the-transaction-being-built) property can be used to restrict read access.
```ts
class Chat extends Contract {
@@ -19,7 +19,7 @@ class Chat extends Contract {
super({
messages: [],
_owners: publicKeys,
- _readers: publicKeys
+ _readers: publicKeys,
})
}
@@ -28,15 +28,15 @@ class Chat extends Contract {
}
remove(publicKey: string) {
- this._readers = this._readers.filter(o => o !== publicKey)
- this._owners_ = this._owners_.filter(o => o !== publicKey)
+ this._readers = this._readers.filter((o) => o !== publicKey)
+ this._owners_ = this._owners_.filter((o) => o !== publicKey)
}
}
```
## Usage
-A new chat can be created using the [`new`](./API/new.md) function. Note that Bob can initially post to the chat and read it's state as Bob's public key was added to the `_owners` array and `_readers` array by Alice upon creation of the chat.
+A new chat can be created using the [`new`](./API/new.md) function. Note that Bob can initially post to the chat and read it's state as Bob's public key was added by Alice to the `_owners` array and to the `_readers` array upon creation of the chat.
Later, Alice called the `remove` function removing Bob's public key from these arrays. After this point Bob cannot read or write anymore.
@@ -58,7 +58,7 @@ const alicesChat = await alice.new(Chat, [publicKeys])
await alicesChat.post('Hi')
// Bob can read the current state of the chat and post a message
-const bobsChat = await bob.sync(alicesChat._rev) as Chat
+const bobsChat = (await bob.sync(alicesChat._rev)) as Chat
await bobsChat.post('Yo')
expect(bobsChat.messages).deep.eq(['Hi', 'Yo'])
@@ -67,7 +67,7 @@ try {
// This line throws an error
await eve.sync(alicesChat._rev)
expect(true).eq(false)
-} catch(err) {
+} catch (err) {
expect(err.message).not.undefined
}
@@ -79,7 +79,11 @@ try {
// This line throws an error
await bob.sync(alicesChat._rev)
expect(true).eq(false)
-} catch(err) {
+} catch (err) {
expect(err.message).not.undefined
}
-```
\ No newline at end of file
+```
+
+## Code
+
+You can find the code [here](https://github.com/bitcoin-computer/monorepo/blob/main/packages/chat/README.md).
diff --git a/packages/docs/Examples/fungible-token.md b/packages/docs/Examples/fungible-token.md
index 542a71ac9..f03ac739c 100644
--- a/packages/docs/Examples/fungible-token.md
+++ b/packages/docs/Examples/fungible-token.md
@@ -7,24 +7,24 @@ icon: circle
## Smart Contract
-A fungible token has three properties, a `supply` indicating the number of tokens stored in the current smart object, a property `totalSupply` that that stores the number of tokens that were created during the mint, and an `_owners` property set to the current owner of the smart object.
+A fungible token has three properties, a `amount` indicating the number of tokens stored in the current smart object, a property `symbol` that stores the identifier of the tokens, and an `_owners` property set to the current owner of the smart object.
-The `transfer` function takes two arguments, an `amount` to be sent and the public key of the recipient. This function first checks if the current smart object contains sufficient supply and throws an error if it does not. If the supply is sufficient the supply of the current smart object is reduced by the amount to be sent. A new smart object is created that is owned by recipient and that contains the amount to be sent. This object is returned from the function call to create a new smart object.
+The `transfer` function takes two arguments, the public key of the recipient and an `amount` to be sent. This function first checks if the current smart object contains sufficient supply and throws an error if it does not. If the supply is sufficient the supply of the current smart object is reduced by the amount to be sent. A new smart object is created that is owned by recipient and that contains the amount to be sent. This object is returned from the function call to create a new smart object.
-```ts
+```javascript
class Token extends Contract {
- supply: number
- totalSupply: number
+ amount: number
+ symbol: string
_owners: string[]
- constructor(to: string, supply: number, totalSupply: number) {
- super({ supply, totalSupply, _owners: [to] })
+ constructor(to: string, amount: number, symbol: string) {
+ super({ _owners: [to], amount, symbol })
}
- transfer(amount: number, recipient: string) {
- if (this.supply < amount) throw new Error()
- this.supply -= amount
- return new Token(recipient, amount, this.totalSupply)
+ transfer(recipient: string, amount: number) {
+ if (this.amount < amount) throw new Error()
+ this.amount -= amount
+ return new Token(recipient, amount, this.symbol)
}
}
```
@@ -42,14 +42,13 @@ const receiver = new Computer()
await sender.faucet(0.001e8)
// Mint new fungible token with total supply of 10
-const token = await sender.new(Token, [sender.getPublicKey(), 10, 10])
+const token = await sender.new(Token, [sender.getPublicKey(), 10, 'MY-TOKEN'])
// Send 2 tokens to receiver, sentToken will have supply of 2 and
// token will have a supply of 8.
-const sentToken = await token.transfer(2, receiver.getPublicKey())
+const sentToken = await token.transfer(receiver.getPublicKey(), 2)
```
## Code
You can find the code [here](https://github.com/bitcoin-computer/monorepo/tree/main/packages/TBC20#readme).
-
diff --git a/packages/docs/Examples/non-fungible-token.md b/packages/docs/Examples/non-fungible-token.md
index 71bc42dba..b649581d2 100644
--- a/packages/docs/Examples/non-fungible-token.md
+++ b/packages/docs/Examples/non-fungible-token.md
@@ -43,7 +43,7 @@ If more than one NFT are broadcast one can save transaction fees by broadcasting
```ts
// Create wallet
-const sender = new Computer(RLTC)
+const sender = new Computer()
// Fund wallet
await sender.faucet(0.001e8)
@@ -58,7 +58,7 @@ await tokenHelper.deploy()
nft = await tokenHelper.mint('name', 'symbol')
// Transfer NFT
-await tokenHelper.transfer(nft._id, new Computer().getPublicKey())
+await tokenHelper.transfer(new Computer().getPublicKey(), nft._id)
```
## Code
diff --git a/packages/docs/Examples/sale.md b/packages/docs/Examples/sale.md
index 9c1f5b501..40ead788f 100644
--- a/packages/docs/Examples/sale.md
+++ b/packages/docs/Examples/sale.md
@@ -15,7 +15,7 @@ These examples use several advanced features (sighash types, mocking, and contro
We first explain a simpler version that works for the Bitcoin Computer but not for ordinals. The [next](#ordinals-sale) section explains a version that can be used with ordinals.
-Seller needs to build a partial transaction containing an input spending the asset and an output for receiving the payment. The [sighash type](https://developer.bitcoin.org/devguide/transactions.html#signature-hash-types) `SIGHASH_SINGLE | SIGHASH_ANYONECANPAY` allows Seller to sign only the first input and output.
+Seller needs to build a partial transaction containing an input spending the asset and an output for receiving the payment. The [sighash type](https://developer.bitcoin.org/devguide/transactions.html#signature-hash-types) `SIGHASH_SINGLE | SIGHASH_ANYONECANPAY` allows Seller to sign only the first input and output.
Buyer wants to obtain the smart object in the first input so Buyer is incentivized to build the transaction according to the protocol. If he broadcasts transaction that is invalid in the Bitcoin Computer protocol, Buyer destroys the smart object but pays the Seller.
@@ -39,7 +39,7 @@ export class Sale extends Contract {
The first argument to the `exec` function is an nft of the following class.
-```ts
+```javascript
export class NFT extends Contract {
constructor(name = '', symbol = '') {
super({ name, symbol })
@@ -109,7 +109,7 @@ class PaymentMock {
const mock = new PaymentMock(1e8)
```
-Now Seller is ready to create and sign the partial sale transaction using as shown below. There is a lot going on, so we will break down the arguments below.
+Now Seller is ready to create and sign the partial sale transaction using as shown below. There is a lot going on here, so we will break down the arguments below.
```ts
const { tx } = await seller.encode({
@@ -165,10 +165,10 @@ Next, Buyer updates the second input of the transaction that currently spends th
tx.updateInput(1, { txId: paymentTxId, index: parseInt(paymentIndex, 10) })
```
-Then Buyer updates the second output to contain Buyer's public key. This ensures that Buyer will be new owner of the nft.
+Then Buyer updates the second output to contain Buyer's public key. This ensures that Buyer will be new owner of the nft.
```ts
-tx.updateOutput(1, { scriptPubKey: buyer.toScriptPubKey()})
+tx.updateOutput(1, { scriptPubKey: buyer.toScriptPubKey() })
```
Finally Buyer funds, signs, and broadcasts to execute the sale.
@@ -282,8 +282,7 @@ await bob.broadcast(finalTx)
The `Sale` smart contract is not safe to use with ordinals because the smart objects have different ordinal ranges before and after the call. To preserve the ordinal ranges the expression must not use the `_amount` keyword and must not return an object or an array containing an object.
-Building a sale contract for ordinals is more complicated than for smart objects. A very clever construction was proposed by Rodarmor [here](https://github.com/ordinals/ord/issues/802) and later [refined](https://github.com/ordinals/ord/issues/802#issuecomment-1498030294). Our smart contract below implements this exact idea.
-
+Building a sale contract for ordinals is more complicated than for smart objects. A very clever construction was proposed by Rodarmor [here](https://github.com/ordinals/ord/issues/802) and later [refined](https://github.com/ordinals/ord/issues/802#issuecomment-1498030294). Our smart contract below implements this exact idea.
### Smart Contracts
@@ -379,7 +378,7 @@ const [paymentTxId, paymentIndex] = payment._rev.split(':')
tx.updateInput(1, { txId: paymentTxId, index: parseInt(paymentIndex, 10) })
// Buyer updates the second output of the swap tx to receive the NFT
-tx.updateOutput(1, { scriptPubKey: buyer.toScriptPubKey()})
+tx.updateOutput(1, { scriptPubKey: buyer.toScriptPubKey() })
// Buyer funds, signs, and broadcasts to execute the sale
await buyer.fund(tx)
diff --git a/packages/docs/Examples/swap.md b/packages/docs/Examples/swap.md
index 0a9f51b69..ea4e98635 100644
--- a/packages/docs/Examples/swap.md
+++ b/packages/docs/Examples/swap.md
@@ -15,7 +15,7 @@ We note that the definition of a token swap differs wildly from the legal defini
## Swap Using a Static Function
-You can build a swap as a static function that takes two arguments and exchanges their owners. This method preserves ordinal ranges, so it is safe to use this smart objects that contain ordinals.
+You can build a swap as a static function that takes two arguments and exchanges their owners. This method preserves ordinal ranges, so it is safe to use this in smart objects that contain ordinals.
### Smart Contracts
@@ -29,9 +29,10 @@ export class StaticSwap extends Contract {
}
}
```
-The code below shows the `NFT` class. While this example uses NFTs as arguments, the same function can be used to swap any pair of smart objects that have a `transfer` function.
-```ts
+The code below shows the `NFT` class. While this example uses NFTs as arguments, the same function can be used to swap any pair of smart objects that have a `transfer` function.
+
+```javascript
export class NFT extends Contract {
constructor(name = '', symbol = '') {
super({ name, symbol })
@@ -54,9 +55,9 @@ const b = await alice.new(NFT, ['B', 'BBB'])
### Building the Swap Transaction
-A swap transaction has two inputs and two outputs. The inputs spend the NFTs to be swapped. The outputs are the NFTs after the swap with their owners exchanged.
+A swap transaction has two inputs and two outputs. The inputs spend the NFTs to be swapped. The outputs are the NFTs after the swap with their owners exchanged.
-Alice passes an expression containing both the code of the `StaticSwap` class and the expression `StaticSwap.exec(a, b)` to the [`encode`](./API/encode.md) function. The second argument is an environment that determines that the values to be used for `a` and `b` are stored at revisions `a._rev` and `b._rev`.
+Alice passes an expression containing both the code of the `StaticSwap` class and the expression `StaticSwap.exec(a, b)` to the [`encode`](../lib/encode.md) function. The second argument is an environment that determines that the values to be used for `a` and `b` are stored at revisions `a._rev` and `b._rev`.
```ts
const { tx } = await alice.encode({
@@ -67,9 +68,11 @@ const { tx } = await alice.encode({
The `encode` function will automatically sign all inputs of the transaction that can be signed with the private key of the computer object on which the function is called. In this case, this is the input as revision `a._rev`.
+The function `encode` will not broadcast automatically. This feature is useful when you want to check the transaction before broadcasting it. It also allows more advanced use cases, for example, using different signature hash types, or signing only specific inputs. More on this in the [API documentation](../lib/encode.md).
+
### Executing the Swap
-Then Bob signs the input `b._rev` and broadcasts the transaction. When the transaction is included in the blockchain the swap is executed and the owners of the two NFTs are reversed.
+The transaction created above was partially signed (only Alice's signature was added). Bob now signs the input `b._rev` and broadcasts the transaction. When the transaction is included in the blockchain the swap is executed and the owners of the two NFTs are reversed.
```ts
await bob.sign(tx)
@@ -104,7 +107,7 @@ await bob.broadcast(tx)
#### Reducing Fees
-The disadvantage of the code above is that the swap class is written into the blockchain on every swap. This wasts block space and is expensive. A more efficient approach is to deploy the `Swap` function as a module first and then refer to the module from the transactions executing the swap. To make this easier, we provide a helper class [`SwapHelper`](https://github.com/bitcoin-computer/monorepo/blob/main/packages/swap/src/swap.ts) for swaps and `NftHelper` for NFTs that can be used as follows:
+The disadvantage of the code above is that the swap class is written into the blockchain on every swap. This wastes block space and is expensive. A more efficient approach is to deploy the `Swap` function as a module first and then refer to the module from the transactions executing the swap. To make this easier, we provide a helper class [`SwapHelper`](https://github.com/bitcoin-computer/monorepo/blob/main/packages/swap/src/swap.ts) for swaps and `NftHelper` for NFTs that can be used as follows:
```ts
// Alice creates helper objects
@@ -138,4 +141,4 @@ await alice.broadcast(tx)
## Code
-Have a look at the code on [Github](https://github.com/bitcoin-computer/monorepo/tree/main/packages/swap#readme) for details.
+Have a look at the code on [Github](https://github.com/bitcoin-computer/monorepo/tree/main/packages/swap#readme) for details.
diff --git a/packages/docs/Lib/broadcast.md b/packages/docs/Lib/broadcast.md
index ff42664a9..a88cad75d 100644
--- a/packages/docs/Lib/broadcast.md
+++ b/packages/docs/Lib/broadcast.md
@@ -3,29 +3,33 @@
The `broadcast` function broadcasts a Bitcoin transaction to the Bitcoin mining network.
### Type
+
```ts
-(tx: BitcoinLib.Transaction) => Promise
+;(tx: BitcoinLib.Transaction) => Promise
```
### Syntax
+
```js
const txId = await computer.broadcast(tx)
```
### Parameters
-#### tx
-A Bitcoin transaction object.
-
+{.compact}
+| Parameter | Description |
+|--------------|---------------------------------------------------------------|
+| tx | A [Bitcoin transaction](https://github.com/bitcoin-computer/monorepo/blob/main/packages/nakamotojs/ts_src/transaction.ts) object.|
### Return value
If broadcast is successful, it returns an string encoding the transaction id. Otherwise, an error is thrown.
### Examples
+
```ts
class C extends Contract {}
const transition = { exp: `${C} new C()` }
const { tx } = await computer.encode(transition)
const txId = await computer.broadcast(tx)
-```
\ No newline at end of file
+```
diff --git a/packages/docs/Lib/constructor.md b/packages/docs/Lib/constructor.md
index 413c6d429..ebf96778d 100644
--- a/packages/docs/Lib/constructor.md
+++ b/packages/docs/Lib/constructor.md
@@ -4,7 +4,7 @@ The constructor of the `Computer` class creates an instance. It's functionality
### Type
-````ts
+```ts
new (config: {
chain?: 'LTC' | 'BTC' | 'DOGE',
network?: 'mainnet' | 'testnet' | 'regtest',
@@ -17,9 +17,10 @@ new (config: {
dustRelayFee?: number,
moduleStorageType?: 'taproot' | 'multisig'
}) => Computer
-````
+```
### Syntax
+
```js
new Computer(config)
```
@@ -27,28 +28,29 @@ new Computer(config)
### Parameters
#### config
+
A configuration object
{.compact}
-| Key | Description | Default Value |
+| Key | Description | Default Value |
|--------------|--------------------------------------------------------------|--------------------------------------|
-| chain | Target blockchain. Values can be 'LTC' or 'BTC' | LTC |
-| network | Target network. Values in 'testnet', 'regtest' or 'mainnet' | regtest |
-| mnemonic | BIP39 mnemonic phrase | Random phrase |
-| path | BIP32 path | m/44'/0'/0' |
-| passphrase | BIP32 passphrase | The empty string |
-| addressType | The address script type. Values in 'p2pkh', 'p2wpkh', 'p2tr' | p2pkh |
-| url | Url of a Bitcoin Computer Node | https://rltc.node.bitcoincomputer.io |
-| satPerByte | Fee in satoshi per byte | 2 |
-| dustRelayFee | Dust relay fee | 30000 on LTC and 3000 on BTC |
-| moduleStorageType | Store ES6 modules on Taproot or multisig scripts | taproot |
-
+| chain | Target blockchain. Values can be 'LTC' or 'BTC' | LTC |
+| network | Target network. Values in 'testnet', 'regtest' or 'mainnet' | regtest |
+| mnemonic | BIP39 mnemonic phrase | Random phrase |
+| path | BIP32 path | m/44'/0'/0' |
+| passphrase | BIP32 passphrase | The empty string |
+| addressType | The address script type. Values in 'p2pkh', 'p2wpkh', 'p2tr' | p2pkh |
+| url | Url of a Bitcoin Computer Node | https://rltc.node.bitcoincomputer.io |
+| satPerByte | Fee in satoshi per byte | 2 |
+| dustRelayFee | Dust relay fee | 30000 on LTC and 3000 on BTC |
+| moduleStorageType | Store ES6 modules on Taproot or multisig scripts | taproot |
### Return Value
An instance of the Computer class
### Examples
+
```ts
import { Computer } from '@bitcoin-computer/lib'
diff --git a/packages/docs/Lib/decode.md b/packages/docs/Lib/decode.md
index 914922fd9..9a5c74952 100644
--- a/packages/docs/Lib/decode.md
+++ b/packages/docs/Lib/decode.md
@@ -2,27 +2,29 @@
The `decode` function parses a Bitcoin transaction to determine if it is a Bitcoin Computer transaction. If so it returns an expression `exp`, a blockchain environment `env`, and a module specifier `mod`. The function `decode` is the inverse of `encode` when the latter is called with `exp`, `env`, and `mod`.
-
### Type
+
```ts
-(tx: BitcoinLib.Transaction) => Promise<{
- exp: string,
- env?: { [s: string]: string },
- mod?: string
-}>
+;(tx: BitcoinLib.Transaction) =>
+ Promise<{
+ exp: string
+ env?: { [s: string]: string }
+ mod?: string
+ }>
```
### Syntax
+
```js
await computer.decode(tx)
```
### Parameters
-#### tx
-
-A [Bitcoin transaction](https://github.com/bitcoin-computer/monorepo/blob/main/packages/nakamotojs/ts_src/transaction.ts) object.
-
+{.compact}
+| Parameter | Description |
+|--------------|---------------------------------------------------------------|
+| tx | A [Bitcoin transaction](https://github.com/bitcoin-computer/monorepo/blob/main/packages/nakamotojs/ts_src/transaction.ts) object. |
### Return value
@@ -36,23 +38,23 @@ type Effect = { res: unknown, env: unknown }
```
If fund is required, and the wallet has insufficient funds, an error is thrown.
-If sign is required, the default behavior is to sign all inputs.
+If sign is required, the default behavior is to sign all inputs.
The encode function will make a best effort to sign all inputs, but will not throw any error if the signature cannot be added due to hash mismatch. This is useful in the case of partially signed transactions, where a user can encode an expression, sign with the user private key and send the generated partially signed transaction to another user. Then, the receiver can sign the remaining inputs.
-
### Examples
+
```ts
class C extends Contract {}
const computer = new Computer()
const transition = {
exp: `${C} new ${C.name}()`,
env: {},
- mod: ''
+ mod: '',
}
const { tx } = await computer.encode(transition)
const decoded = await computer.decode(tx)
expect(decoded).to.deep.equal(transition)
-```
\ No newline at end of file
+```
diff --git a/packages/docs/Lib/deploy.md b/packages/docs/Lib/deploy.md
index 33c0be57e..4c67c42ab 100644
--- a/packages/docs/Lib/deploy.md
+++ b/packages/docs/Lib/deploy.md
@@ -11,29 +11,32 @@ Please note that modules are not encrypted, even if objects that use them have t
There are two different modes to store a module on the blockchain: `taproot` or `multisig` mode. The default mode is `taproot`. The mode can be changed by passing the option `moduleStorageType` into the constructor of the `Computer` class. In Taproot mode, the module is stored in a Taproot script. This is cheeper and it enables you to store larger Javascript programs in a module. The multisig mode stores the module in multisig scripts. This is more expensive but compatible with chains that do not support Taproot.
### Type
+
```ts
-(module: string) => Promise
+;(module: string) => Promise
```
### Syntax
+
```js
const rev = await computer.deploy(exp)
```
### Parameters
-#### module
-A string encoding an ES6 module.
+{.compact}
+| Parameter | Description |
+|--------------|---------------------------------------------------------------|
+| module | A string encoding an ES6 module.|
### Return value
-A string encoding the location where the module is stored. The format is \:\
@@ -51,6 +48,10 @@ npm run up
+!!!
+The node will create the docker volumes in the `packages/node/chain-setup/**` directory of the selected chain and network. This folder contains the blockchain data and the database. The postgres database is used to efficiently store the complete blockchain data, for fast access and indexing.
+!!!
+
### Run the Tests
You can run the integration tests with the command below.
@@ -63,7 +64,7 @@ npm run test
-On regtest, the halving period is set to infinity. This makes it possible to run a large number of tests without having to restart the node.
+On Litecoin regtest, the halving period is set to infinity. This makes it possible to run a large number of tests without having to restart the node.
### Fund the Wallet
@@ -73,10 +74,10 @@ In regtest mode, you can fund a wallet with the following commands.
```sh
# Fund Litecoin regtest wallet
-npm run fund:ltc -- ...
+npm run fund ltc ...
# Fund Bitcoin regtest wallet
-npm run fund:btc -- ...
+npm run fund btc ...
```
@@ -88,7 +89,7 @@ You can stop the node with the command below. When you restart the process, it w
```sh
-npm run down -- -r
+npm run down
```
@@ -100,7 +101,7 @@ The command below will reset the database, delete all blockchain data, and stop
```sh
-npm run reset
+npm run clean
```
@@ -113,27 +114,27 @@ The [Bitcoin Computer Library](https://github.com/bitcoin-computer/monorepo/tree
```js
// Import client side library
-import { Computer } from "@bitcoin-computer/lib";
+import { Computer } from '@bitcoin-computer/lib'
// Configuration to connect to node on localhost
const conf = {
- chain: "LTC",
- network: "regtest",
- url: "http://localhost:1031",
-};
+ chain: 'LTC',
+ network: 'regtest',
+ url: 'http://localhost:1031',
+}
// Create instance of client side library
-const computer = new Computer(conf);
-const address = computer.getAddress();
+const computer = new Computer(conf)
+const address = computer.getAddress()
// Fund client side library
-const { txId, vout } = await computer.faucet(1e4);
+const { txId, vout } = await computer.faucet(1e4)
// Return the utxos
-expect(await new Computer(conf).getUtxos(address)).deep.eq([`${txId}:${vout}`]);
+expect(await new Computer(conf).getUtxos(address)).deep.eq([`${txId}:${vout}`])
// Return the balance
-expect(await new Computer(conf).getBalance(address).balance).eq(1e4);
+expect(await new Computer(conf).getBalance(address).balance).eq(1e4)
// Return the transactions
expect(await new Computer(conf).listTxs(address)).deep.eq({
@@ -146,7 +147,7 @@ expect(await new Computer(conf).listTxs(address)).deep.eq({
satoshis: 1e4,
},
],
-});
+})
```
@@ -277,33 +278,7 @@ The following table shows the times and costs for syncing to a Litecoin node on
| 8 | 32GB | 7h 15m | $240 |
| 16 | 32GB | 4h 45m | $440 |
-->
+
## Versioning
If you run your own node, make sure to use the same versions of Lib and Node.
-
-## Documentation
-
-Have a look at the [docs](https://docs.bitcoincomputer.io/).
-
-## Getting Help
-
-If you have any questions, please let us know on Telegram, Twitter, or by email clemens@bitcoincomputer.io.
-
-## Development Status
-
-See [here](https://github.com/bitcoin-computer/monorepo/tree/main/packages/lib#development-status).
-
-## Price
-
-See [here](https://github.com/bitcoin-computer/monorepo/tree/main/packages/lib#price).
-
-## License
-
-This software is licensed under the [Creative Commons Attribution-NoDerivs 3.0 Unported](https://creativecommons.org/licenses/by-nd/3.0/) license.
-
-You are free to: share, copy, and redistribute the material in any medium or format for any purpose, even commercially under the following terms:
-
-- Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
-- NoDerivatives — If you remix, transform, or build upon the material, you may not distribute the modified material.
-
-This is a human-readable summary of (and not a substitute for) the [license](https://creativecommons.org/licenses/by-nd/3.0/legalcode).
diff --git a/packages/docs/README.md b/packages/docs/README.md
index 2e39b0ea9..d802ab5f9 100644
--- a/packages/docs/README.md
+++ b/packages/docs/README.md
@@ -1,5 +1,5 @@
-
TBC Documentation
+
Bitcoin Computer Documentation
The official documentation of the Bitcoin Computer
diff --git a/packages/docs/how-it-works.md b/packages/docs/how-it-works.md
index 83dfe1d02..96b578dad 100644
--- a/packages/docs/how-it-works.md
+++ b/packages/docs/how-it-works.md
@@ -7,14 +7,13 @@ icon: light-bulb
## Intuition
-In a Bitcoin Computer transaction, a JavaScript expression is embedded within a standard Bitcoin transaction. The result of evaluating this expression is linked to an output. If the result contains objects, each of these objects is assigned to a separate output.
+The Bitcoin Computer embeds JavaScript expression in standard Bitcoin transactions. This expression is evaluated, and the result of that evaluation determines the transaction's outputs. If the JavaScript expression evaluates to a primitive value (e.g., number, string, boolean) or an object without sub-objects, that value is used to create a single output. If the expression evaluates to a JavaScript object with sub-objects, the object and each of its sub-objects is mapped to a separate output. This enables the creation of multiple outputs from a single expression.
-For expressions with an undefined variable (for example, the variable `x` is undefined in the expression `x + 1`), the smart contract developer can associate that variables with an input of the transaction. The Bitcoin Computer then recursively calculates the values of these outputs, and replaces the undefined variables with their computed values from previous transactions to evaluate the expression.
+A key feature is the ability to handle dependencies on data not directly available within the current transaction. For expressions with an undefined variable (for example, the variable `x` is undefined in the expression `x + 1`), the smart contract developer can associate that variables with an input of the transaction. The Bitcoin Computer then recursively calculates the values of these outputs, and replaces the undefined variables with their computed values from previous transactions to evaluate the expression.
### Basic Example
-
-
-
@@ -26,21 +25,21 @@ In this example, the transaction is inscribed with the arithmetic expression `1+
### Smart Contracts and Objects
-We will refer to a Javascript expression that is inscribed in a transaction as a *smart contract*. The value that such an expression evaluates to is called a *smart value*. If a smart value is of object type we refer to it as a *smart object*.
+In the tutorial section, we introduced the concept of Smart Contract, typically referred as Javascript classes that extends from `Contract`. We also introduced the concept of Smart Object, which are instances of these classes. In this section, we will provide a more formal definition of these concepts.
-In the Bitcoin Computer system, JavaScript expressions embedded within transactions are called smart contracts. The values of these expressions is known as a smart values. When a smart value is of an object type, it is referred to as a smart object. This terminology is borrowed from object oriented programming and helps distinguish between a class and the objects created from such a class.
+In the Bitcoin Computer system, we refer to a _smart contract_ as any valid JavaScript expression that is inscribed in a transaction. The value that such an expression evaluates to is called a _smart value_. When a smart value is of an object type, it is referred to as a smart object. This terminology is borrowed from object oriented programming and helps distinguish between a class and instances of that class, i.e. the objects created from such a class.
### Data Ownership
-In the TBC system, data ownership is linked to the ability to spend an output, similar to the ownership of Bitcoin. A “smart object embedded in a transaction is the property of the user(s) who can spend that output. For enhanced security and ownership clarity, every “smart object” includes an `_owners` property, listing the public keys of its owners. Conversely, if an object is created with a property `_owners` that is set to an array of $n$ string encoded public keys, then the output that represents the object has a $1$-of-$n$ multisig script with these public keys.
+In the Bitcoin Computer, data ownership is linked to the ability to spend an output, similar to the ownership of Bitcoin. For enhanced security and ownership clarity, every “smart object” includes an `_owners` property, listing the public keys of its owners. Conversely, if an object is created with a property `_owners` that is set to an array of $n$ string encoded public keys, then the output that represents the object has a $1$-of-$n$ multisig script with these public keys.
### Creating Objects and Object Identity
-Associating values with transaction outputs facilitates the use of the transaction ID and output number as a unique identifier for each smart object. This identifier is assigned to the _id property of the smart object upon its creation and remains unchanged for the object’s entire lifespan.
+Associating values with transaction outputs facilitates the use of the transaction ID and output number as a unique identifier for each smart object. This identifier is assigned to the `_id` property of the smart object upon its creation and remains unchanged for the object’s entire lifespan.
### Updating Objects and Object Revisions
-When a smart object is updated, a transaction is broadcast that spends the old state’s utxo with new one, reflecting the object’s updated state. This transaction ID and output number are designated as the object’s revision and stored in the `_rev` property of the object. This mechanism ensures that each update is traceable and securely linked to the specific transaction.
+When a smart object is updated, a transaction is broadcast that spends the old state’s UTXO with new one, reflecting the object’s updated state. This transaction ID and output number are designated as the object’s revision and stored in the `_rev` property of the object. This mechanism ensures that each update is traceable and securely linked to the specific transaction.
### Ancestors and Roots of Objects
@@ -56,7 +55,7 @@ The code on the left side of the picture below defines a class `NFT` with two pr

-The right side of the picture shows a transaction in which both the class and a constructor call is inscribed. This expression evaluates to a new object of class `NFT`. It also shows that all three special properties `_id`, `_rev`, `_root_` are assigned the same value: the transaction id of the transaction shown and output number 1 (we represent this string as a blue circle in the picture).
+The right side of the picture shows a transaction in which both the class and a constructor call is inscribed. This expression evaluates to a new object of class `NFT`. It also shows that all three special properties `_id`, `_rev`, `_root` are assigned the same value: the transaction id of the transaction shown and the first output (we represent this string as a blue circle in the picture).
The picture below shows the same object after two updates. First, the expression `nft.send('038e2...')` is evaluated where `nft` refers to the object immediately after the constructor call. The second update is due to the evaluation of the expression `nft.send('03f0b...')` where this time `nft` refers to the object after the first update. We can see that the revision is changed after every update but the identity and the root stays the same.
@@ -70,7 +69,7 @@ The figure below illustrates the minting and sending of 100 fungible tokens. The

-The blue output of the second transaction represents the 97 tokens that the blue user still holds, while the green output represents the three tokens now owned by the green user. The _root property of both outputs in the second transaction is linked to the output of the first transaction, as the memory cell for the three tokens was allocated within a function call.
+The blue output of the second transaction represents the 97 tokens that the blue user still holds, while the green output represents the three tokens now owned by the green user. The `_root` property of both outputs in the second transaction is linked to the output of the first transaction, as the memory cell for the three tokens was allocated within a function call.
This setup prevents forgery, as any two tokens with the same root can be traced back to the same mint. To mint a second token with the same root, one would have to broadcast a transaction with the transaction id of the first transaction, which is impossible.
diff --git a/packages/docs/index.md b/packages/docs/index.md
index 464793dcf..521f56dae 100644
--- a/packages/docs/index.md
+++ b/packages/docs/index.md
@@ -6,21 +6,20 @@ layout: page
# Introduction
-The Bitcoin Computer (TBC) is a Turing-complete smart contract system for Bitcoin and Litecoin, designed for creating decentralized applications. With TBC, you can create tokens, exchanges, games, social networks, and more.
+The Bitcoin Computer is a Turing-complete metaprotocol for UTXO-Based Blockchains, designed for creating decentralized applications in Bitcoin, Litecoin and compatible blockchains like Dogecoin and Pepecoin (Bitcoin Cash coming soon). You can create tokens, exchanges, games, social networks, and more.
-**Free Computation.** A key feature of TBC is that execution costs do not depend on the computational complexity of the smart contract itself. Unlike other systems where costs escalate with computational intensity, TBC maintains a fixed cost for an unlimited number of computational steps.
+**Free Computation.** A key feature of the Bitcoin Computer is that execution costs do not depend on the computational complexity of the smart contract itself. Unlike other systems where costs escalate with computational intensity, the Bitcoin Computer maintains a fixed cost for an unlimited number of computational steps.
-**JavaScript and TypeScript Support.** Smart contracts on TBC are built using JavaScript or TypeScript classes, ensuring fluid integration with web applications. This compatibility leverages the robust JavaScript ecosystem, simplifying development and enhancing functionality.
+**JavaScript and TypeScript Support.** Smart contracts are built using JavaScript or TypeScript classes, ensuring fluid integration with web applications. This compatibility leverages the robust JavaScript ecosystem, simplifying development and enhancing functionality.
-**How it works.** To deploy a smart contract on TBC, simply inscribe a JavaScript class. You can then instantiate your smart contract by inscribing a constructor call, creating a “smart object”. Updates to this object are managed through subsequent inscribed function calls, enabling dynamic interactions within your application.
+**How it works.** To deploy a smart contract, simply inscribe a JavaScript class. You can then instantiate your smart contract by inscribing a constructor call, creating a “smart object”. Updates to this object are managed through subsequent inscribed function calls, enabling dynamic interactions within your application.
+**Data Ownership.** Each smart object resides within a UTXO (Unspent Transaction Output). The owner of the UTXO is the only entity authorized to modify the object’s state, reflecting a natural approach to data ownership that mirrors the security associated with Bitcoin transactions.
-**Data Ownership.** In TBC, each smart object resides within a UTXO (Unspent Transaction Output). The owner of the UTXO is the only entity authorized to modify the object’s state, reflecting a natural approach to data ownership that mirrors the security associated with Bitcoin transactions.
+**Historical States.** Every transaction on the Bitcoin Computer records an update, allowing for the recovery of every historical state of a smart object. This history includes details on who made updates and when, providing a comprehensive audit trail for each object.
-**Historical States.** Every transaction on TBC records an update, allowing for the recovery of every historical state of a smart object. This history includes details on who made updates and when, providing a comprehensive audit trail for each object.
+**Encryption and Off Chain Storage.** By default, every user can read the states of smart objects on the Bitcoin Computer. However, the platform includes built-in support for end-to-end encryption and off-chain data storage. These features facilitate the development of applications that adhere to consumer protection regulations such as the CCPA and GDPR, ensuring both security and compliance.
-**Encryption and Off Chain Storage.** By default, every user can read the states of smart objects on TBC. However, the platform includes built-in support for end-to-end encryption and off-chain data storage. These features facilitate the development of applications that adhere to consumer protection regulations such as the CCPA and GDPR, ensuring both security and compliance.
+**Pure Bitcoin.** Finally, this framework relies only on Bitcoin. It does not require a side-chain or an extra token. This makes it possible to build applications that are as trustless as Bitcoin.
-**Pure Bitcoin.** Finally, TBC relies only on Bitcoin. It does not require a side-chain or an extra token. This makes it possible to build applications that are as trustless as Bitcoin.
-
-**Contact.** TBC is being developed by BCDB Inc. If you have any questions, please let us know in our [Telegram group](https://t.me/thebitcoincomputer), on [Twitter](https://twitter.com/TheBitcoinToken), or by email at clemens@bitcoincomputer.io.
+**Contact.** The Bitcoin Computer is being developed by BCDB Inc. If you have any questions, please let us know in our [Telegram group](https://t.me/thebitcoincomputer), on [Twitter](https://twitter.com/TheBitcoinToken), or by email at clemens@bitcoincomputer.io.
diff --git a/packages/docs/language.md b/packages/docs/language.md
index e7e3c74fa..8ad80b8e1 100644
--- a/packages/docs/language.md
+++ b/packages/docs/language.md
@@ -6,9 +6,10 @@ icon: log
# Smart Contract Language
The Bitcoin Computer uses Javascript with slight modifications. Specifically:
-* *Property assignments are not permitted outside function calls.* This makes it possible to impose constraints on all future values of an object, thereby making Javascript a viable smart contract language
-* *Certain keyword properties have a special semantics.* This gives the smart contract programmer fine grained control over the transaction being built.
-* *Assignments to `this` is not permitted in constructor calls.* This is necessary for internal reasons to ensure the first two properties.
+
+- _Property assignments are not permitted outside function calls._ This makes it possible to impose constraints on all future values of an object, thereby making Javascript a viable smart contract language
+- _Certain keyword properties have a special semantics._ This gives the smart contract programmer fine grained control over the transaction being built.
+- _Assignments to `this` is not permitted in constructor calls._ This is necessary to ensure the first two properties.
These properties are technically enforced by the requirement that all objects returned from a smart contract inherit from a class `Contract` that is exported from the Bitcoin Computer Library.
@@ -29,35 +30,34 @@ class Even extends Contract {
const even = new Even()
```
-Calling `even.inc2()` works as expected.
+Calling `await even.inc2()` works as expected.
+
```js
-even.inc2()
+await even.inc2()
expect(even.n).eq(2)
```
However, assigning to `even.n` outside of a function call throws an error.
-``` js
+
+```js
try {
even.n = 3
expect(true).eq(false)
-} catch(err) {
+} catch (err) {
expect(err.message).eq("Cannot set property 'n' directly")
}
```
-
-
-While this is not a very useful example for a constraint, all smart contracts are based on constraints to future values in a similar way.
+While this is not a very useful example for a constraint, all smart contracts are based on constraints to future values in a similar way.
### Special Semantics of Keyword Properties
The Bitcoin Computer uses special properties (called keyword properties) that
-* control details of the transaction being build, and
-* give the user information as to where on the blockchain a smart object was created and where it is currently stored.
-
-```ts
+- control details of the transaction being build, and
+- give the user information as to where on the blockchain a smart object was created and where it is currently stored.
+```ts
type SmartObject = OutputDetails & Location
```
@@ -69,25 +69,30 @@ Properties named `_amount`, `_owners`, `_readers`, and `_url` provide control ov
```ts
type OutputDetails = {
- // determines which users can update the object
- _owners?: string[]
+ // determines which users can update the object
+ _owners?: string[] | string
// determines number of Satoshis stored in the output associated with the object
_amount?: number
// determines whether object is encrypted and who can decrypt it
_readers?: string[]
-
+
// determines if data is stored off-chain
_url?: string
}
```
The effect that these properties have on the transaction being built is described below:
-* If a property `_amount` is set it needs to be set to a number. It determines the amount of Satoshi stored in the output representing the current revision. If it is not set the revision will have a minimal (non-dust) amount of Satoshi.
-* If a property `_owners` is set it needs to be set to an array of strings $[p_1\ ...\ p_n]$. These determine the output script of the current revision. Specifically, the script for the current revision is a 1-of-n multisig script with the public keys $p_1\ ...\ p_n$. This guarantees that only a user that has a private key corresponding to one of the public keys can update the object. If the property is not set it defaults to the public key of the computer that created the object.
-* If a property `_readers` is set it needs to be set to an array of strings $[p_1\ ...\ p_n]$. If this property is set the meta data in the corresponding transaction is encrypted such that only users with corresponding private keys can decrypt the expression and compute the value of the smart object. If the `_readers` property is not set the meta data is not encrypted and any user can compute the value of the smart object.
-* If a property `_url` is set it needs to be set to the url of a Bitcoin Computer node. If it is set the expression is not stored in the transaction but on the node instead. The transaction only contains a hash of the expression and the location where the expression can be obtained from the node. This is convenient if the expression is large, for example because it contains a lot of data.
+
+- If a property `_amount` is set it needs to be set to a number. It determines the amount of Satoshi stored in the output representing the current revision. If it is not set the revision will have a minimal (non-dust) amount of Satoshi.
+- If a property `_owners` is set it needs to be set to either an array of strings $[p_1\ ...\ p_n]$ or to a string.
+
+ - Array of strings: These determine the output script of the current revision. Specifically, the script for the current revision is a 1-of-n multisig script with the public keys $p_1\ ...\ p_n$. This guarantees that only a user that has a private key corresponding to one of the public keys can update the object. If the property is not set it defaults to the public key of the computer that created the object.
+ - String: If the property is set to a string $p$, it should be set to an ASM representation of a script. This script is used as the output script of the current revision. This allows for more complex ownership conditions. For example, the script could be non-standard or it could be a multisig script with a different number of required signatures than 1.
+
+- If a property `_readers` is set it needs to be set to an array of strings $[p_1\ ...\ p_n]$. If this property is set the meta data in the corresponding transaction is encrypted such that only users with corresponding private keys can decrypt the expression and compute the value of the smart object. If the `_readers` property is not set the meta data is not encrypted and any user can compute the value of the smart object.
+- If a property `_url` is set it needs to be set to the url of a Bitcoin Computer node. If it is set the expression is not stored in the transaction but on the node instead. The transaction only contains a hash of the expression and the location where the expression can be obtained from the node. This is convenient if the expression is large, for example because it contains a lot of data.
#### Location Keyword Properties
@@ -105,9 +110,10 @@ type Location = {
readonly _root: string
}
```
-* The value of the `_id` property is the output (encoded as \:\) that represented the object immediately after it was created.
-* The value of the `_rev` property is the output of the currently representing the object (that is, the object's revision).
-* The value of the `_root` property is assigned once when the object is created and is never modified subsequently. If the expression that creates the object is of the form `new C(...)` then its root is equal to its id. If the expression is of the form `x.f(...)` then the root of the new object is equal to the id of `x`. Otherwise the root is set to `n/a`. The root property is useful for building fungible tokens.
+
+- The value of the `_id` property is the output (encoded as \:\) that represented the object immediately after it was created.
+- The value of the `_rev` property is the output of the currently representing the object (that is, the object's revision).
+- The value of the `_root` property is assigned once when the object is created and is never modified subsequently. If the expression that creates the object is of the form `new C(...)` then its root is equal to its id. If the expression is of the form `x.f(...)` then the root of the new object is equal to the id of `x`. Otherwise the root is set to `n/a`. The root property is useful for building fungible tokens.
### Assigning to `this` in Constructors is Prohibited
@@ -121,7 +127,7 @@ class A extends Contract {
}
```
-This has the same effect as setting assigning to `this` in a normal Javascript program
+This has the same effect as assigning to `this` in a normal Javascript program
```js
// Not a smart contract, for illustration purposes only
@@ -132,4 +138,4 @@ class A {
this.kn = vn
}
}
-```
\ No newline at end of file
+```
diff --git a/packages/docs/start.md b/packages/docs/start.md
index be3a785f5..417fd758b 100644
--- a/packages/docs/start.md
+++ b/packages/docs/start.md
@@ -3,7 +3,6 @@ order: -10
icon: rocket
---
-
# Start
## Use in the Browser
@@ -13,9 +12,12 @@ The easiest way to try the Bitcoin Computer is to create a file as below and ope
```html
-
- Value: *
+ Value: *
```
@@ -132,7 +133,7 @@ Counter {
-In the setup above you are using a node that we provide at `node.bitcoincomputer.io`. You can use this node for free but it is rate limited. For serious development we recommend to clone the monorepo so you can run your own, unlimited, node.
+In the setup above you are using a node that we provide at `rltc.node.bitcoincomputer.io` (Litecoin Regtest). You can use this node for free but it is rate limited. For serious development we recommend to clone the monorepo so you can run your own, unlimited, node.
## Run a Node
@@ -165,8 +166,6 @@ cp chain-setup/ltc/regtest/litecoin.conf.example litecoin.conf
npm run up
```
-The node will create the docker volumes in the `packages/node/chain-setup/**` directory of the selected chain and network. This folder contains the blockchain data and the database.
-
### Test
Once the node is up an running, open a separate terminal window and navigate the monorepo folder. You can run the following commands
@@ -186,16 +185,16 @@ The commands will be run in each package. You can also navigate the a package an
### Start your own Project
-We provide two templates, `vite-template` for client side projects and `node-template` for server side projects, featuring:
-* Bitcoin Computer
-* Typescript
-* Eslint
-* Testing environment
+We provide two templates, [`vite-template`](https://github.com/bitcoin-computer/monorepo/tree/main/packages/vite-template) for client side projects and [`node-template`](https://github.com/bitcoin-computer/monorepo/tree/main/packages/nodejs-template) for server side projects, featuring:
+
+- Bitcoin Computer
+- Typescript
+- Eslint
+- Testing environment
The easiest thing to do is just to rename the folder. Alternatively have a look at our example apps (e.g. our [wallet](https://wallet.bitcoincomputer.io/), [blockchain explorer](https://explorer.bitcoincomputer.io/), or [nft app](https://nft.bitcoincomputer.io/)) to see if any of them are a good starting point for your project.
## Getting Help
-* [Telegram](https://t.me/thebitcoincomputer)
-* [Twitter](https://twitter.com/TheBitcoinToken)
-
+- [Telegram](https://t.me/thebitcoincomputer)
+- [Twitter](https://twitter.com/TheBitcoinToken)
diff --git a/packages/docs/tutorial.md b/packages/docs/tutorial.md
index 4f8c064f8..66574ec40 100644
--- a/packages/docs/tutorial.md
+++ b/packages/docs/tutorial.md
@@ -5,10 +5,9 @@ icon: mortar-board
# Tutorial
-
## Write a Smart Contract
-Smart contracts are Javascript or Typescript classes that extend from ``Contract``. For example, a smart contract for a simple chat is
+Smart contracts are typically Javascript or Typescript classes that extend from `Contract`. For example, a smart contract for a simple chat is
```js
import { Contract } from '@bitcoin-computer/lib'
@@ -24,7 +23,13 @@ class Chat extends Contract {
}
```
-Note that it is not possible to assign to ``this`` in constructors. Instead you can initialize a smart object by passing an argument into ``super`` as shown above.
+!!!success **Smart Object**
+Given a class that extends from `Contract`, we define a **smart object** as an instance of that class that is deployed to the blockchain. Smart objects are the basic building blocks of the Bitcoin Computer.
+!!!
+
+You can notice that there are specific rules to follow when writing a smart contract. To deep dive into the rules and best practices, check out the [Smart Contract Language](/language/).
+
+
## Create a Computer Object
@@ -36,17 +41,17 @@ import { Computer } from '@bitcoin-computer/lib'
const computer = new Computer({ mnemonic: 'replace this seed' })
```
-You can pass in a [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) mnemonic to initialize the wallet in the computer object. To securely generate a random mnemonic leave the ``mnemonic`` key undefined. You can find more configuration options [here](/api/constructor/).
+You can pass in a [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) mnemonic to initialize the wallet in the computer object. To securely generate a random mnemonic leave the `mnemonic` key undefined. You can find more configuration options [here](/lib/constructor/).
## Create a Smart Object
-The [``computer.new``](/api/new) function creates a smart object from a smart contract.
+The [`computer.new`](/api/new) function creates a smart object from a smart contract.
```js
const chat = await computer.new(Chat, ['hello'])
```
-The object ``chat`` that is returned has the properties defined in the class and five extra properties ``_id``, ``_rev``, ``_root``, ``_owners`` and ``_amount``.
+Basically, the `Chat` class is inscribed into a Bitcoin transaction and broadcast to the network, and an instance of the class is returned. In the example, the object `chat` has the properties defined in the `Chat` class and five extra properties `_id`, `_rev`, `_root`, `_owners` and `_amount`.
```js
expect(chat).to.deep.equal({
@@ -55,13 +60,13 @@ expect(chat).to.deep.equal({
_rev: '667c...2357:0',
_root: '667c...2357:0',
_owners: ['03...'],
- _amount: 5820
+ _amount: 5820,
})
```
-The property ``_owners`` is an array of public keys that are able to spend that UTXO and the property ``_amount`` is the amount of satoshis in that UTXO. The meaning of the other properties are explained below.
+The `_owners` property lists the public keys able to spend this UTXO. The `_amount` property specifies the UTXO's value in satoshis.
-The properties `_id`, `_rev`, `_root` reference a transaction that is broadcast when the expression `await computer.new(Chat, ['hello'])` is evaluated. This transaction encodes the expression
+The properties `_id`, `_rev`, `_root` reference a transaction that is broadcast when the expression `await computer.new(Chat, ['hello'])` is evaluated. This transaction encodes the class definition and the creation of an instance of the class, as in following expression:
```js
class Chat extends Contract {
@@ -81,17 +86,18 @@ Another user can download this transaction and evaluate this expression to obtai
## Read a Smart Object
-The [``computer.sync``](/api/sync) function computes the state of smart object. For example, synchronizing to ``667c...2357:0`` will return an object with the same value as ``chat``.
+The [`computer.sync`](/api/sync) function computes the state of smart object. For example, synchronizing to `667c...2357:0` will return an object with the same value as `chat`.
```js
expect(await computer.sync('667c...2357:0')).to.deep.equal(chat)
```
+The [`computer.sync`](/api/sync) function computes the state of the smart object by recursively evaluating all the transactions that reference the smart object, and replaying the expressions in those transactions.
You can find more details about how this works [here](./how-it-works.md#storing-values).
## Update a Smart Object
-A Smart object can be updated by calling one of it's functions. Note that you have to ``await`` on all function calls to read the latest state.
+A smart object can be updated by calling one of it's functions. Note that you have to `await` on all function calls to read the latest state.
```js
await chat.post('world')
@@ -102,20 +108,19 @@ expect(chat).to.deep.equal({
_rev: 'de43...818a:0',
_root: '667c...2357:0',
_owners: ['03...'],
- _amount: 5820
+ _amount: 5820,
})
```
-When a function is called, a transaction is broadcast that inscribes the expression of the function call. In the example, the transaction with id ``de43...818a`` inscribes the expression
+When a function is called, a transaction that inscribes the expression of the function call is broadcast. In the example, the transaction with id `de43...818a` inscribes the expression:
```js
chat.post('world')
```
-Note that the ``_rev`` property of the ``chat`` object has been updated to ``de43...818a:0``. Every time a smart object is updated a new *revision* is created. The corresponding transaction id and output number is assigned to the ``_rev`` property. The ``_id`` property is never updated and is a unique identifier for each smart object. You can find more details about updating smart object [here](./how-it-works.md#updating-values).
-
+The `_id` property uniquely identifies each smart object and remains constant. However, the `_rev` property changes with each update, tracking the different versions of the object. For instance, the chat object's current revision is `de43...818a:0`. Each update creates a new `_rev` value, composed of the transaction ID and output number. This means one `_id` can be associated with multiple `_rev` values, reflecting its update history. Further details on updating smart objects can be found [here](./how-it-works.md#updating-values).
-The ``computer.sync`` function maps revisions to historical states. It can be called with any historical revision. It will return the current state for the latest revision.
+The `computer.sync` function maps revisions to historical states. It can be called with any historical revision. It will return the current state for the latest revision.
```js
const oldChat = await computer.sync(chat._id)
@@ -127,14 +132,14 @@ expect(newChat.messages).to.deep.equal(['hello', 'world'])
## Find a Smart Object
-The [``computer.query``](/api/query) function returns the latest revision of a smart objects. It can be called with many different kinds of arguments, for example object one or more ids:
+The [`computer.query`](/api/query) function returns the latest revision of a smart objects. It can be called with many different kinds of arguments, for example object one or more ids:
```js
-const [rev] = await computer.query({ ids: ['667c...2357:0']})
+const [rev] = await computer.query({ ids: ['667c...2357:0'] })
expect(rev).to.equal('de43...818a:0')
```
-A basic pattern for many applications is to identify a smart object by its id, look up the object's latest revision using ``computer.query``, and then to compute its latest state using ``computer.sync``. For example, imagine a chat app where the url would contain the id of a specific chat. The app could compute the latest state of the chat as follows:
+A basic pattern for many applications is to identify a smart object by its ids, look up the object's latest revision using `computer.query`, and then to compute its latest state using `computer.sync`. For example, imagine a chat app where the url would contain the id of a specific chat. The app could compute the latest state of the chat as follows:
```js
const urlToId = (url) => ...
@@ -145,9 +150,9 @@ const obj = await computer.sync(rev)
## Data Ownership
-Every smart object can have up to three owners. Only an owner can update the object. The owners can be set by assigning string encoded public keys to the ``_owners`` property of a smart object. If the ``_owners`` property is not assigned in a smart contract it defaults to the public key of the computer object that created the smart object.
+Every smart object can have up to three owners. Only an owner can update the object. The owners can be set by assigning an array of string encoded public keys to the `_owners` property of a smart object. If the `_owners` property is not assigned in a smart contract it defaults to the public key of the computer object that created the smart object.
-In the chat example the initial owner is the public key of the ``computer`` object on which ``computer.new`` function was called. Thus only a user with the private key for that public key will be able to post to the chat. We can add a function `invite` to update the owners array to allow more users to post.
+In the chat example the initial owner is the public key of the `computer` object on which `computer.new` function was called. Thus only a user with the private key for that public key will be able to post to the chat. We can add a function `invite` to update the owners array to allow more users to post.
```js
class Chat extends Contract {
@@ -159,9 +164,11 @@ class Chat extends Contract {
}
```
+It is also possible to set the `_owners` property to an ASM representation of a script that defines the ownership rules. This allows for more complex conditions over the data ownership. To get more information on how to use this feature see the [Smart Contract Language](./language.md/#control-keyword-properties) section.
+
## Privacy
-By default, the state of all smart objects is public in the sense that any user can call the ``computer.sync`` function on an object's revision. However, you can restrict read access to an object by setting its ``_readers`` property to an array of public keys. If ``_readers`` is assigned, the meta-data on the transaction is encrypted using a combination of AES and ECIES. Only the specified readers can decrypt an encrypted object using the ``computer.sync`` function.
+By default, the state of all smart objects is public in the sense that any user can call the `computer.sync` function on an object's revision. However, you can restrict read access to an object by setting its `_readers` property to an array of public keys. If `_readers` is assigned, the meta-data on the transaction is encrypted using a combination of AES and ECIES. Only the specified readers can decrypt an encrypted object using the `computer.sync` function.
For example, if we want to ensure that only people invited to the chat can read the messages, we can update our example code as follows:
@@ -170,7 +177,7 @@ class Chat extends Contract {
constructor(greeting, owner) {
super({
messages: [greeting],
- _readers: [owner]
+ _readers: [owner],
})
}
@@ -211,7 +218,7 @@ class Chat extends Contract {
## Cryptocurrency
-Each smart object can store an amount of cryptocurrency. By default a smart object stores a minimal (non-dust) amount. If the ``_amount`` property of a smart object is set to a number, the output storing that smart object will contain that number of satoshis. For example, consider the class ``Payment`` below.
+Each smart object can store an amount of cryptocurrency. By default a smart object stores a minimal (non-dust) amount. If the `_amount` property of a smart object is set to a number, the output storing that smart object will contain that number of satoshis. For example, consider the class `Payment` below.
```js
class Payment extends Contract {
@@ -225,14 +232,14 @@ class Payment extends Contract {
}
```
-If a user *A* wants to send 210000 satoshis to a user *B*, the user *A* can setup the payment as follows:
+If a user _A_ wants to send 210000 satoshis to a user _B_, the user _A_ can setup the payment as follows:
```js
const computerA = new Computer({ mnemonic: })
const payment = computerA.new(Payment, [210000])
```
-When the ``payment`` smart object is created, the wallet inside the ``computerA`` object funds the 210000 satoshi that are stored in the ``payment`` object. Once user *B* becomes aware of the payment, he can withdraw by syncing against the object and calling the ``cashOut`` function.
+When the `payment` smart object is created, the wallet inside the `computerA` object funds the 210000 satoshi that are stored in the `payment` object. Once user _B_ becomes aware of the payment, he can withdraw by syncing against the object and calling the `cashOut` function.
```js
const computerB = new Computer({ seed: })
@@ -240,4 +247,56 @@ const paymentB = await computerB.sync(payment._rev)
await paymentB.cashOut()
```
-One more transaction is broadcast for which user *B* pays the fees. This transaction has two outputs: one that records that the ``cashOut`` function was called with 546 satoshi and another that spends the remaining satoshi to user *B*'s address.
+When executing the `cashOut` function one more transaction is broadcast which send the satoshis to user _B_'s address.
+
+## Advanced Topics
+
+Until now, we use the Bitcoin Computer in a very simple way. However, the Bitcoin Computer is a powerful tool that can be used to build complex applications.
+
+### The `computer.encode()` function
+
+One of the most powerful features of the Bitcoin Computer is the ability to encode Javascript expressions into a Bitcoin transaction that can be stored on the blockchain. This allows for a low-level control over the Bitcoin Computer's execution environment.
+
+The `computer.encode()` function builds a Bitcoin transaction from a Javascript expression according to the [Bitcoin Computer protocol](../how-it-works.md). In addition to the transaction, this function also returns the value of the expression.
+
+For example, the following code creates a Bitcoin transaction that can be deployed to the blockchain, with a Javascript expression that encodes a smart contract class definition and creates a new instance of the smart contract.
+
+```js
+class C extends Contract {} // define a simple smart contract class
+
+const { tx } = await computer.encode({ exp: `${C} new ${C.name}()` })
+```
+
+The encode function can compute the updated status of the objects or expressions in the transaction. This is useful to check the status of the objects before deploying the transaction.
+
+To get more information on this functionality and other advanced options see the [`computer.encode()`](./lib/encode) section of the API documentation.
+
+### Module System
+
+The Bitcoin Computer includes a flexible module system that allows you to deploy and import modules from the blockchain. This is useful for sharing code between different smart contracts and applications, to import modules inside of smart contracts, and to save on deployment costs.
+
+To deploy a module to the blockchain, you can use the `computer.deploy()` function. This function takes a Javascript expression that defines the module, and deploys it to the blockchain. The function returns the address of the deployed module (transaction ID).
+
+In the following example, a simple class `A` is deployed to the blockchain, and then a class `B` is deployed that imports `A` from the blockchain.
+
+```js
+const revA = await computer.deploy(`export class A extends Contract {}`)
+
+const revB = await computer.deploy(`
+ import { A } from '${revA}'
+ export class B extends A {}
+`)
+const { tx } = await computer.encode({ exp: `new B()`, mod: revB })
+expect(tx.getId()).to.be.a.string
+```
+
+To import a module from the blockchain, you can use the `computer.load(rev)` function. This function takes the location of the module and returns the module.
+
+```ts
+class A extends Contract {}
+const rev = await computer.deploy(`export ${A}`)
+const { A: AA } = await computer.load(rev)
+expect(AA).to.equal(A)
+```
+
+To deep dive into the module system and other advanced options see the [`computer.deploy()`](./lib/deploy) and the [`computer.load()`](./lib/load) section of the API documentation.
diff --git a/packages/nodejs-template/README.md b/packages/nodejs-template/README.md
index 65c429f17..848ed3a83 100644
--- a/packages/nodejs-template/README.md
+++ b/packages/nodejs-template/README.md
@@ -1,6 +1,5 @@
-
-
TBC Node.js Template
+
Bitcoin Computer Node.js Template
A template for Node.js with TypeScript and the Bitcoin Computer
@@ -72,6 +71,7 @@ Have a look at the [docs](https://docs.bitcoincomputer.io/) for the Bitcoin Comp
If you have any questions, please let us know on Telegram, Twitter, or by email clemens@bitcoincomputer.io.
## Development Status
+
See [here](https://github.com/bitcoin-computer/monorepo/tree/main/packages/lib#development-status).
## Price
@@ -99,8 +99,6 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[node]: https://github.com/bitcoin-computer/monorepo/tree/main/packages/node
-
-
[ts-badge]: https://img.shields.io/badge/TypeScript-4.5-blue.svg
[nodejs-badge]: https://img.shields.io/badge/Node.js->=%2016.13-blue.svg
[nodejs]: https://nodejs.org/dist/latest-v14.x/docs/api/
diff --git a/packages/swap/README.md b/packages/swap/README.md
index 0082f58fb..cecf9388b 100644
--- a/packages/swap/README.md
+++ b/packages/swap/README.md
@@ -1,6 +1,5 @@
-
-
TBC Swaps
+
Bitcoin Computer Swaps
A collection of swap smart contracts for the Bitcoin Computer
@@ -11,11 +10,12 @@
This package contains the following smart contracts:
-* [Swap](./src/swap.ts). A static swap function for two smart objects.
-* [Swappable](./src/swappable.ts). A NFT contract with a built in swap method.
-* [Sale](./src/sale.ts). A contract for selling a smart object for a pre-determined amount of satoshis. This contract does not preserve ordinal ranges so it cannot be used to sell ordinals.
-* [OrdSale](./src/ord-sale.ts). An contract for selling an ordinal for a pre-determined amount of satoshis.
-* [TxWrapper](./src/tx-wrapper.ts). A contract for storing a partially signed transaction in another transaction. This is useful for communicating partially signed transactions over the Bitcoin network.
+
+- [Swap](./src/swap.ts). A static swap function for two smart objects.
+- [Swappable](./src/swappable.ts). A NFT contract with a built in swap method.
+- [Sale](./src/sale.ts). A contract for selling a smart object for a pre-determined amount of satoshis. This contract does not preserve ordinal ranges so it cannot be used to sell ordinals.
+- [OrdSale](./src/ord-sale.ts). An contract for selling an ordinal for a pre-determined amount of satoshis.
+- [TxWrapper](./src/tx-wrapper.ts). A contract for storing a partially signed transaction in another transaction. This is useful for communicating partially signed transactions over the Bitcoin network.
## Prerequisites
@@ -81,6 +81,7 @@ Have a look at the [docs](https://docs.bitcoincomputer.io/) for the Bitcoin Comp
If you have any questions, please let us know on
Telegram,
Twitter, or by email clemens@bitcoincomputer.io.
## Development Status
+
See [here](https://github.com/bitcoin-computer/monorepo/tree/main/packages/lib#development-status).
## Price
@@ -108,8 +109,6 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[node]: https://github.com/bitcoin-computer/monorepo/tree/main/packages/node
-
-
[ts-badge]: https://img.shields.io/badge/TypeScript-4.5-blue.svg
[nodejs-badge]: https://img.shields.io/badge/Node.js->=%2016.13-blue.svg
[nodejs]: https://nodejs.org/dist/latest-v14.x/docs/api/
diff --git a/packages/vite-template/README.md b/packages/vite-template/README.md
index 34cc2597d..79360472e 100644
--- a/packages/vite-template/README.md
+++ b/packages/vite-template/README.md
@@ -1,7 +1,7 @@
-
TBC CRA Template
+
Bitcoin Computer Vite Template
- A template for Create React App with TypeScript and the Bitcoin Computer
+ A template for Create Vite App with TypeScript and the Bitcoin Computer
website · docs
@@ -28,11 +28,7 @@ npm install
-## Usage
-
-Most of the api is documented in the [Create React App Readme](https://github.com/facebook/create-react-app).
-
-### Start the Application
+## Start the Application
To start the application run the command below and open [http://localhost:3000](http://localhost:3000).
@@ -63,6 +59,7 @@ Have a look at the [docs](https://docs.bitcoincomputer.io/) for the Bitcoin Comp
If you have any questions, please let us know on
Telegram,
Twitter, or by email clemens@bitcoincomputer.io.
## Development Status
+
See [here](https://github.com/bitcoin-computer/monorepo/tree/main/packages/lib#development-status).
## Price
diff --git a/packages/website/README.md b/packages/website/README.md
index 625d1c5c7..288208bda 100644
--- a/packages/website/README.md
+++ b/packages/website/README.md
@@ -1,5 +1,5 @@
-
TBC Website
+
Bitcoin Computer Website
The official Bitcoin Computer Website