From 05343eb1c9ef94a212c96b44b8b44ed12de9703a Mon Sep 17 00:00:00 2001 From: ltardivo Date: Thu, 13 Feb 2025 17:41:00 -0300 Subject: [PATCH 01/19] Adds Bitcoin Computer Node API to docs --- packages/docs/node.md | 468 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 448 insertions(+), 20 deletions(-) diff --git a/packages/docs/node.md b/packages/docs/node.md index c384c49af..88fffbde2 100644 --- a/packages/docs/node.md +++ b/packages/docs/node.md @@ -1,6 +1,5 @@ --- order: -60 -icon: package --- # Node @@ -49,6 +48,8 @@ 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. The postgres database is used to efficiently store the complete blockchain data, for fast access and indexing. + ### Run the Tests @@ -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 ``` @@ -277,33 +278,460 @@ 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 +## Api + +The Bitcoin Computer Node exposes an API that can be used to interact with the node. +The variables `CHAIN` and `NETWORK` are used to define the chain and network that the node is running on. + +### Wallet + +#### `/v1/CHAIN/NETWORK/wallet/:address/utxos` + +Returns the UTXOs for a given address. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/wallet/mwJn1YPMq7y5F8J3LkC5Hxg9PHyZ5K4cFv/utxos +``` + +```json +[ + { + "address": "mkMUZNoiLh4uuuENU5HNZ4Ssxo8BqEQc5t", + "satoshis": 99927794, + "asm": "OP_DUP OP_HASH160 350dbb89c08f5b4aa19eb2bc0b4bb8ba5b79a873 OP_EQUALVERIFY OP_CHECKSIG", + "rev": "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89:3", + "txId": "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89", + "vout": 3 + } +] +``` + +#### `/v1/CHAIN/NETWORK/address/:address/balance` + +Returns the confirmed, unconfirmed and total balance for a given address. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/address/mkMUZNoiLh4uuuENU5HNZ4Ssxo8BqEQc5t/balance +``` + +```json +{ + "confirmed": 99927794, + "unconfirmed": 0, + "balance": 99927794 +} +``` + +#### `/v1/CHAIN/NETWORK/wallet/:address/sent-outputs` + +Returns the outputs that were sent from a given address. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/wallet/mkMUZNoiLh4uuuENU5HNZ4Ssxo8BqEQc5t/sent-outputs +``` + +```json +[ + { + "output": "9343ce7ca5e2039ab5329b2918319bd1656983cf2e8f8de7c4001d61870d0eb8:1", + "amount": 99961718 + }, + { + "output": "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89:1", + "amount": 99944756 + } +] +``` + +#### `/v1/CHAIN/NETWORK/wallet/:address/received-outputs` + +Returns the outputs that were received by a given address. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/wallet/mkMUZNoiLh4uuuENU5HNZ4Ssxo8BqEQc5t/received-outputs +``` + +```json +[ + { + "output": "db98c59f328bb45b14a957ce44546f5bfe2f1bf4394de18e98f32188e76082be:5", + "amount": 99961718 + }, + { + "output": "9343ce7ca5e2039ab5329b2918319bd1656983cf2e8f8de7c4001d61870d0eb8:3", + "amount": 99944756 + }, + { + "output": "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89:3", + "amount": 99927794 + } +] +``` + +#### `/v1/CHAIN/NETWORK/wallet/:address/list-txs` + +Returns the sent and received transactions for a given address. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/wallet/mkMUZNoiLh4uuuENU5HNZ4Ssxo8BqEQc5t/list-txs +``` + +```json +{ + "sentTxs": [ + { + "txId": "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89", + "inputsSatoshis": 99944756, + "outputsSatoshis": 99927794, + "satoshis": 16962 + }, + { + "txId": "9343ce7ca5e2039ab5329b2918319bd1656983cf2e8f8de7c4001d61870d0eb8", + "inputsSatoshis": 99961718, + "outputsSatoshis": 99944756, + "satoshis": 16962 + } + ], + "receivedTxs": [ + { + "txId": "db98c59f328bb45b14a957ce44546f5bfe2f1bf4394de18e98f32188e76082be", + "inputsSatoshis": 0, + "outputsSatoshis": 99961718, + "satoshis": 99961718 + } + ] +} +``` + +### Transactions + +#### `/v1/CHAIN/NETWORK/tx/bulk` + +Returns the raw transaction for a given list of transaction IDs. + +```shell +curl -X POST http://localhost:1031/v1/LTC/regtest/tx/bulk \ + -H "Content-Type: application/json" \ + -d '{ + "txIds": [ + "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89", + "9343ce7ca5e2039ab5329b2918319bd1656983cf2e8f8de7c4001d61870d0eb8", + "db98c59f328bb45b14a957ce44546f5bfe2f1bf4394de18e98f32188e76082be" + ] + }' +``` + +```json +[ + "0100000002b80e0d87611d00c4...", + "0100000001b80e0d87611d00c4...", + "0100000000012b087e18328f98..." +] +``` + +#### `/v1/CHAIN/NETWORK/tx/post` + +Posts a raw transaction to the network. + +```shell +curl -X POST http://localhost:1031/v1/LTC/regtest/tx/post \ + -H "Content-Type: application/json" \ + -d '{ + "hex": "0100000002b80e0d87611d00c4..." + }' +``` + +```json +"e53c1440f547b51343d46a2acaafe127e915c7ed08a7ef2ed0ffc248360c0cca" +``` + +#### `/v1/CHAIN/NETWORK/tx/:txId/ancestors` + +Returns the ancestors of a given transaction. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/tx/e53c1440f547b51343d46a2acaafe127e915c7ed08a7ef2ed0ffc248360c0cca/ancestors +``` + +```json +[ + "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89", + "9343ce7ca5e2039ab5329b2918319bd1656983cf2e8f8de7c4001d61870d0eb8", + "db98c59f328bb45b14a957ce44546f5bfe2f1bf4394de18e98f32188e76082be" +] +``` + +#### `/v1/CHAIN/NETWORK/tx/:txId/json` + +Returns the JSON representation of a given transaction. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/tx/e53c1440f547b51343d46a2acaafe127e915c7ed08a7ef2ed0ffc248360c0cca/json +``` + +```json +{ + "txId": "e53c1440f547b51343d46a2acaafe127e915c7ed08a7ef2ed0ffc248360c0cca", + "txHex": "0100000001202aabc...", + "vsize": 443, + "version": 1, + "locktime": 0, + "ins": [ + { + "txId": "7c2f4dacaeac0a69c451bdd19f6c31d54def13b76ec8687160468d0ac8ab2a20", + "vout": 0, + "script": "47304402203...", + "sequence": 4294967295 + } + ], + "outs": [ + { + "address": "mryiaVyu9cDrdYCGzt8TimdxXPS1vmJS1a", + "script": "512102ff3...", + "value": 5820 + }, + { + "address": "mryiaVyu9cDrdYCGzt8TimdxXPS1vmJS1a", + "script": "76a9147db...", + "value": 99971398 + } + ] +} +``` + +### Blockchain + +#### `/v1/CHAIN/NETWORK/mine` + +Mine an specific number of blocks to a random address. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/mine?count=1 +``` + +```json +{ "success": true } +``` + +#### `/v1/CHAIN/NETWORK/:id/height` -Have a look at the [docs](https://docs.bitcoincomputer.io/). +Get the height an specific block. The `id` can be `best` or a block given hash. -## Getting Help +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/best/height +``` -If you have any questions, please let us know on Telegram, Twitter, or by email clemens@bitcoincomputer.io. +```json +{ "height": 101 } +``` -## Development Status +#### `/v1/CHAIN/NETWORK/rpc` -See [here](https://github.com/bitcoin-computer/monorepo/tree/main/packages/lib#development-status). +Make a RPC call to the node. -## Price +```shell +curl -X POST http://localhost:1031/v1/LTC/regtest/rpc \ + -H "Content-Type: application/json" \ + -d '{ + "method": "getmempoolinfo", + "params": "" + }' +``` -See [here](https://github.com/bitcoin-computer/monorepo/tree/main/packages/lib#price). +```json +{ + "result": { + "result": { + "loaded": true, + "size": 1, + "bytes": 144, + "usage": 1296, + "maxmempool": 300000000, + "mempoolminfee": 0.00001, + "minrelaytxfee": 0.00001, + "unbroadcastcount": 1 + }, + "error": null, + "id": 40795 + } +} +``` -## License +### Regtest Faucet -This software is licensed under the [Creative Commons Attribution-NoDerivs 3.0 Unported](https://creativecommons.org/licenses/by-nd/3.0/) license. +#### `/v1/CHAIN/NETWORK/faucet` -You are free to: share, copy, and redistribute the material in any medium or format for any purpose, even commercially under the following terms: +Send coins to an address. -- 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. +```shell +curl -X POST http://localhost:1031/v1/LTC/regtest/faucet \ + -H "Content-Type: application/json" \ + -d '{ + "address": "mkMUZNoiLh4uuuENU5HNZ4Ssxo8BqEQc5t", + "value": "100000000" + }' +``` -This is a human-readable summary of (and not a substitute for) the [license](https://creativecommons.org/licenses/by-nd/3.0/legalcode). +```json +{ + "txId": "68ef61b6c8896c42f983a0a80caa299ba8cfb0d9d03431ee5bcd6fbf7e0aa21b", + "vout": 0, + "height": -1, + "satoshis": "100000000" +} +``` + +#### `v1/CHAIN/NETWORK/faucetScript` + +Send coins to a script. + +```shell +curl -X POST http://localhost:1031/v1/LTC/regtest/faucetScript \ + -H "Content-Type: application/json" \ + -d '{ + "script": "76a914f7f1", + "value": "100000000" + }' +``` + +```json +{ + "txId": "68ef61b6c8896c42f983a0a80caa299ba8cfb0d9d03431ee5bcd6fbf7e0aa21b", + "vout": 0, + "height": -1, + "satoshis": "100000000" +} +``` + +### Query revisions + +#### `/v1/CHAIN/NETWORK/revs` + +Get the revisions of a list of transactions. + +```shell +curl -X POST http://localhost:1031/v1/LTC/regtest/revs \ + -H "Content-Type: application/json" \ + -d '{ + "ids": [ + "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89", + "9343ce7ca5e2039ab5329b2918319bd1656983cf2e8f8de7c4001d61870d0eb8" + ] + }' +``` + +```json +[ + "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89", + "db98c59f328bb45b14a957ce44546f5bfe2f1bf4394de18e98f32188e76082be" +] +``` + +#### `/v1/CHAIN/NETWORK/rev/:revToId` + +Given a revision, returns the id of the smart contract. + +```shell +curl -X POST http://localhost:1031/v1/LTC/regtest/revToId \ + -H "Content-Type: application/json" \ + -d '{ + "rev": "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89:0" + }' +``` + +```json +"db98c59f328bb45b14a957ce44546f5bfe2f1bf4394de18e98f32188e76082be:0" +``` + +#### `/v1/CHAIN/NETWORK/next/:rev` + +Get the next revision of a given revision. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/next/032fc7a37e7848f5fb2beb79f773631c6047be0a2e9a699e1355aa8d1c64155e:0 +``` + +```json +{ "rev": "44a1e658be5b1fa7b13511979c91497cacf9286aac694bbb75188b875384db98:0" } +``` + +#### `/v1/CHAIN/NETWORK/prev/:rev` + +Get the previous revision of a given revision. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/prev/44a1e658be5b1fa7b13511979c91497cacf9286aac694bbb75188b875384db98:0 +``` + +```json +{ "rev": "032fc7a37e7848f5fb2beb79f773631c6047be0a2e9a699e1355aa8d1c64155e:0" } +``` + +#### `/v1/CHAIN/NETWORK/non-standard-utxos` + +Query revisions by module specifier, public key, limit, order, offset and list of transaction ids. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/non-standard-utxos?mod=1 +curl -X GET http://localhost:1031/v1/LTC/regtest/non-standard-utxos?publicKey=02e3b0... +curl -X GET http://localhost:1031/v1/LTC/regtest/non-standard-utxos?limit=10 +curl -X GET http://localhost:1031/v1/LTC/regtest/non-standard-utxos?order=DESC +curl -X GET http://localhost:1031/v1/LTC/regtest/non-standard-utxos?offset=10 + +id="4446faf2ea02713580152f2355bc91e2eac3649c85e38d882e1ca795bb7b1494:0" +json_array=$(jq -n --arg id "$id" '[$id]') +encoded_json=$(echo "$json_array" | jq -r @uri) +url="http://localhost:1031/v1/LTC/regtest/non-standard-utxos?ids=$encoded_json" +curl -X GET "$url" +``` + + + +```json +["4446faf2ea02713580152f2355bc91e2eac3649c85e38d882e1ca795bb7b1494:0"] +``` + +### OffChain + +#### `/v1/store/:id` + +Get the data stored in the offchain storage. + +```shell +curl -X GET http://localhost:1031/v1/store/fcdb882a0b9556a0c6fb2a89efe0633f0c256f24696f465d386a91803838e79a +``` + +```json +{ + "exp": "class A extends Contract { + constructor(n, url){ + super({ + n: n, + _url: url + }); + + } + } + new A(0.2815266905953051,'http://localhost:1031')", + "env":{}, + "mod":"", + "v":"0.24.0-beta.0" +} +``` + +#### `/v1/store` + +Stores the hex of the data in the offchain storage. + +```shell +curl -X POST http://localhost:1031/v1/store \ + -H "Content-Type: application/json" \ + -d '{ + "data": "{\"exp\":\"3+1\"}" + }' +``` From b0294e1132e0b98a893274b6c3dec2dee7d80e8c Mon Sep 17 00:00:00 2001 From: ltardivo Date: Thu, 13 Feb 2025 17:41:19 -0300 Subject: [PATCH 02/19] Adds .prettierrc to docs --- packages/docs/.prettierrc | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 packages/docs/.prettierrc 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" +} From 2ab8fb1403fdabe857f2098abbc2ecca92f5e413 Mon Sep 17 00:00:00 2001 From: ltardivo Date: Thu, 13 Feb 2025 18:26:38 -0300 Subject: [PATCH 03/19] Fixes node instructions. Adds prettier --- packages/docs/start.md | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/packages/docs/start.md b/packages/docs/start.md index be3a785f5..7f219f347 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 @@ -187,15 +186,15 @@ 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 + +- 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) From 63fe154ed9ea001b14166779037a31f19f034e4e Mon Sep 17 00:00:00 2001 From: ltardivo Date: Thu, 13 Feb 2025 19:55:31 -0300 Subject: [PATCH 04/19] Improves index --- packages/docs/index.md | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/packages/docs/index.md b/packages/docs/index.md index 464793dcf..8fcbc1111 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 smart contracts 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. From f60f4ece68098100ceebff77d16cf8e0d84a819a Mon Sep 17 00:00:00 2001 From: ltardivo Date: Thu, 13 Feb 2025 19:55:41 -0300 Subject: [PATCH 05/19] Improves tutorial page --- packages/docs/tutorial.md | 59 +++++++++++++++++++++------------------ 1 file changed, 32 insertions(+), 27 deletions(-) diff --git a/packages/docs/tutorial.md b/packages/docs/tutorial.md index 4f8c064f8..d56d716bb 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 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. +=== :paperclip: **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 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 { @@ -161,7 +166,7 @@ class Chat extends Contract { ## 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 +175,7 @@ class Chat extends Contract { constructor(greeting, owner) { super({ messages: [greeting], - _readers: [owner] + _readers: [owner], }) } @@ -211,7 +216,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 +230,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 +245,4 @@ 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. From 9aae7deb53557c9179c81e408b81fb8101e69036 Mon Sep 17 00:00:00 2001 From: ltardivo Date: Thu, 13 Feb 2025 20:33:24 -0300 Subject: [PATCH 06/19] More work on tutorial and how it works --- packages/docs/README.md | 2 +- packages/docs/how-it-works.md | 19 +++++++++---------- packages/docs/tutorial.md | 2 +- 3 files changed, 11 insertions(+), 12 deletions(-) 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..d92f07470 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. +Bitcoin Computer transactions embed a JavaScript expression within a standard Bitcoin transaction. This expression is evaluated, and the result of that evaluation directly determines the transaction's outputs. If the JavaScript expression evaluates to a primitive value (e.g., number, string, boolean), that value is used to create a single output. If the expression evaluates to a JavaScript object, each property of that object is mapped to a separate output. The value of the property becomes the value of the 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 ![](/static/legend@1x.png)- - -![](/static/int-example@1x.png) @@ -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 unspent transaction outputs (UTXOs) 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 ![](/static/nft-create@1x.png) -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 ![](/static/ft-create@1x.png) -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/tutorial.md b/packages/docs/tutorial.md index d56d716bb..4a2ce7cd7 100644 --- a/packages/docs/tutorial.md +++ b/packages/docs/tutorial.md @@ -7,7 +7,7 @@ icon: mortar-board ## 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' From fb148426b77a887912705c09ff2f57f38effde13 Mon Sep 17 00:00:00 2001 From: ltardivo Date: Fri, 14 Feb 2025 12:28:20 -0300 Subject: [PATCH 07/19] Uses product name --- packages/chat/README.md | 2 +- packages/chess-app/README.md | 4 ++-- packages/chess-contracts/README.md | 2 +- packages/chess-server/README.md | 2 +- packages/components/README.md | 19 ++++++++++--------- packages/nodejs-template/README.md | 6 ++---- packages/swap/README.md | 17 ++++++++--------- packages/vite-template/README.md | 3 ++- packages/website/README.md | 2 +- 9 files changed, 28 insertions(+), 29 deletions(-) diff --git a/packages/chat/README.md b/packages/chat/README.md index e9da1ab96..b89b9e840 100644 --- a/packages/chat/README.md +++ b/packages/chat/README.md @@ -1,5 +1,5 @@

-

TBC Chat

+

Bitcoin Computer Chat

A chat that's as stable as Bitcoin and Litecoin
diff --git a/packages/chess-app/README.md b/packages/chess-app/README.md index 4c91e3a06..b9e100da7 100644 --- a/packages/chess-app/README.md +++ b/packages/chess-app/README.md @@ -1,8 +1,8 @@ -# Chess App +# Bitcoin Computer Chess App ## Usage -Start a Bitcoin Computer Node in the package `node`. Then copy the `.env.example` file. +Start a Bitcoin Computer Node in the package `node`. Then copy the `.env.example` file. ``` cp .env.example .env diff --git a/packages/chess-contracts/README.md b/packages/chess-contracts/README.md index 9c7e85e2b..8465f36e4 100644 --- a/packages/chess-contracts/README.md +++ b/packages/chess-contracts/README.md @@ -1,4 +1,4 @@ -# Chess Contracts +# Bitcoin Computer Chess Contracts ## Usage diff --git a/packages/chess-server/README.md b/packages/chess-server/README.md index 551a63ec8..23088cd8d 100644 --- a/packages/chess-server/README.md +++ b/packages/chess-server/README.md @@ -1,4 +1,4 @@ -# Chess Server +# Bitcoin Computer Chess Server ## Usage diff --git a/packages/components/README.md b/packages/components/README.md index a3b25608e..990468934 100644 --- a/packages/components/README.md +++ b/packages/components/README.md @@ -1,5 +1,5 @@

-

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/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..fe4b77f51 100644 --- a/packages/vite-template/README.md +++ b/packages/vite-template/README.md @@ -1,5 +1,5 @@
-

TBC CRA Template

+

Bitcoin Computer CRA Template

A template for Create React App with TypeScript and the Bitcoin Computer
@@ -63,6 +63,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
From 1ce08841a8819c2d643054fe4bd63bd76415a25e Mon Sep 17 00:00:00 2001 From: ltardivo Date: Fri, 14 Feb 2025 12:28:29 -0300 Subject: [PATCH 08/19] Removes unused contract --- packages/chat/src/contracts/counter.ts | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 packages/chat/src/contracts/counter.ts diff --git a/packages/chat/src/contracts/counter.ts b/packages/chat/src/contracts/counter.ts deleted file mode 100644 index ab3f09338..000000000 --- a/packages/chat/src/contracts/counter.ts +++ /dev/null @@ -1,10 +0,0 @@ -export class Counter extends Contract { - count!: number - constructor() { - super({ count: 0 }) - } - - inc() { - this.count += 1 - } -} From 68c5e8d82387329bc11a00112e28e91fc515990d Mon Sep 17 00:00:00 2001 From: ltardivo Date: Fri, 14 Feb 2025 12:29:17 -0300 Subject: [PATCH 09/19] More work on docs --- packages/docs/Examples/chat.md | 22 +++--- packages/docs/Examples/fungible-token.md | 27 ++++---- packages/docs/Examples/non-fungible-token.md | 4 +- packages/docs/Examples/sale.md | 15 ++--- packages/docs/Examples/swap.md | 19 +++--- packages/docs/Lib/encode.md | 70 +++++++++++--------- packages/docs/language.md | 52 ++++++++------- 7 files changed, 111 insertions(+), 98 deletions(-) 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..32b4d9d4a 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, o 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/encode.md b/packages/docs/Lib/encode.md index a81b1461f..5c39dd2ed 100644 --- a/packages/docs/Lib/encode.md +++ b/packages/docs/Lib/encode.md @@ -10,36 +10,43 @@ Other options can customize the funding and signing process. !!!success The state update effected by a Bitcoin Computer transaction is completely predictable: -* If the transaction is included in a block the new state will be exactly the state returned from the `effect` function. -* If the transaction is not included the state is not updated. -!!! + +- If the transaction is included in a block the new state will be exactly the state returned from the `effect` function. +- If the transaction is not included the state is not updated. + !!! ### Type + ```ts -(opts: { - exp: string, // an expression - env?: Record, // a blockchain environment +;(opts: { + exp: string // an expression + env?: Record // a blockchain environment mod?: string // a module specifier // Funding options fund?: boolean // whether to fund the transaction include?: string[] // include specific UTXOs when funding exclude?: string[] // exclude specific UTXOs when funding - + // Signing options sign?: boolean // whether to sign the transaction sighashType?: number // Sighash type to use - index?: number // input index to be signed + inputIndex?: number // input index to be signed inputScript?: Buffer // use input script (instead of signing) -}) => Promise<{ - // the transaction with the expression inscribed - tx: BitcoinLib.Transaction, - // the result of the evaluation - effect: { res: Json; env: Json } -}> + + // Mock options + mocks?: Record // a mock environment +}) => + Promise<{ + // the transaction with the expression inscribed + tx: BitcoinLib.Transaction + // the result of the evaluation + effect: { res: Json; env: Json } + }> ``` ### Syntax + ```js await computer.encode({ exp }) await computer.encode({ exp, env }) @@ -51,23 +58,23 @@ await computer.encode({ exp, fund, sign }) ### Parameters #### opts -An object with the basic configuration parameters to encode the expression in a transaction. - +An object with the basic configuration parameters to encode the expression in a transaction. {.compact} -| Key | Type | Description | Default Value | +| Key | Type | Description | Default Value | |-------------|------------------------|--------------------------------------------------------------------------------------------------------|---------------| -| exp | string | A Javascript expression | | -| env | Record | A Blockchain environment, maps free variables to latest revisions | \{\} | -| mod | string | A module specifier | undefined | -| fund | boolean | Whether the transaction should be funded | true | -| include | string[] | UTXOs to include when funding | [] | -| exclude | string[] | UTXOs to exclude when funding | [] | -| sign | boolean | Whether to sign the transaction | true | -| sighashType | number | The sighash type | 1=SIGHASH_ALL | -| index | number | If set to an number the corresponding input is signed. If undefined all inputs are signed. | undefined | -| inputScript | string | If set to a string a custom input script can be provided. If undefined a signature script is generated | undefined | +| exp | string | A Javascript expression | | +| env | Record | A Blockchain environment, maps free variables to latest revisions | \{\} | +| mod | string | A module specifier | undefined | +| fund | boolean | Whether the transaction should be funded | true | +| include | string[] | UTXOs to include when funding | [] | +| exclude | string[] | UTXOs to exclude when funding | [] | +| sign | boolean | Whether to sign the transaction | true | +| sighashType | number | The sighash type | 1=SIGHASH_ALL | +| inputIndex | number | If set to an number the corresponding input is signed. If undefined all inputs are signed. | undefined | +| inputScript | string | If set to a string a custom input script can be provided. If undefined a signature script is generated | undefined | +| mocks | Record | A pair . The object is an instance of a mocked class (A class that does not extends from Contract but has the keywords `_id`, `_root`, `_amount`,`_owners`) | undefined | Module specifiers and UTXOs are encoded as strings of the form \:\ @@ -83,13 +90,12 @@ The transaction `tx` is an object from the [NakamotoJS](https://github.com/bitco The `res` object contains the result of the evaluation. -The `env` object has the same keys as the blockchain environment. However, whereas the values of the blockchain environment are revision strings, the values of `env` and the smart object at these revisions *after* evaluating the expression. - +The `env` object has the same keys as the blockchain environment. However, whereas the values of the blockchain environment are revision strings, the values of `env` and the smart object at these revisions _after_ evaluating the expression. - ### Examples + ```ts import { Computer, Contract } from '@bitcoin-computer/lib' @@ -109,7 +115,7 @@ const { effect, tx } = await computer.encode({ // Effect captures state of smart objects // if the transaction is broadcast expect(effect).deep.eq({ - res: { + res: { n:1 _id: '667c...2357:0', _rev: '667c...2357:0', @@ -129,4 +135,4 @@ const synced = await computer.sync(txId) // The new state in memory will always equal effect expect(synced).deep.eq(effect) -``` \ No newline at end of file +``` diff --git a/packages/docs/language.md b/packages/docs/language.md index e7e3c74fa..a729b904c 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,7 +69,7 @@ Properties named `_amount`, `_owners`, `_readers`, and `_url` provide control ov ```ts type OutputDetails = { - // determines which users can update the object + // determines which users can update the object _owners?: string[] // determines number of Satoshis stored in the output associated with the object @@ -77,17 +77,18 @@ type OutputDetails = { // 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 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. #### Location Keyword Properties @@ -105,9 +106,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 +123,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 +134,4 @@ class A { this.kn = vn } } -``` \ No newline at end of file +``` From 33b80b86ed26a2a547d6501d48de360c3d2e180e Mon Sep 17 00:00:00 2001 From: ltardivo Date: Fri, 14 Feb 2025 18:28:43 -0300 Subject: [PATCH 10/19] Adds node API in different pages --- packages/docs/Node/API/Blockchain/height.md | 13 + packages/docs/Node/API/Blockchain/mine.md | 13 + packages/docs/Node/API/Blockchain/rpc.md | 33 + packages/docs/Node/API/Offchain/id.md | 27 + packages/docs/Node/API/Offchain/store.md | 13 + .../docs/Node/API/Query-revisions/next.md | 13 + .../API/Query-revisions/non-standard-utxos.md | 25 + .../docs/Node/API/Query-revisions/prev.md | 13 + .../docs/Node/API/Query-revisions/revs.md | 23 + .../docs/Node/API/Query-revisions/revtoid.md | 17 + .../docs/Node/API/Regtest-faucet/faucet.md | 23 + .../Node/API/Regtest-faucet/faucetScript.md | 23 + .../docs/Node/API/Transaction/ancestors.md | 17 + packages/docs/Node/API/Transaction/bulk.md | 21 + packages/docs/Node/API/Transaction/json.md | 39 + packages/docs/Node/API/Transaction/post.md | 17 + packages/docs/Node/API/Wallet/balance.md | 17 + packages/docs/Node/API/Wallet/list-txs.md | 36 + .../docs/Node/API/Wallet/received-outputs.md | 26 + packages/docs/Node/API/Wallet/sent-outputs.md | 22 + packages/docs/Node/API/Wallet/utxos.md | 22 + packages/docs/Node/API/api.md | 59 ++ packages/docs/Node/node.md | 284 +++++++ packages/docs/node.md | 737 ------------------ 24 files changed, 796 insertions(+), 737 deletions(-) create mode 100644 packages/docs/Node/API/Blockchain/height.md create mode 100644 packages/docs/Node/API/Blockchain/mine.md create mode 100644 packages/docs/Node/API/Blockchain/rpc.md create mode 100644 packages/docs/Node/API/Offchain/id.md create mode 100644 packages/docs/Node/API/Offchain/store.md create mode 100644 packages/docs/Node/API/Query-revisions/next.md create mode 100644 packages/docs/Node/API/Query-revisions/non-standard-utxos.md create mode 100644 packages/docs/Node/API/Query-revisions/prev.md create mode 100644 packages/docs/Node/API/Query-revisions/revs.md create mode 100644 packages/docs/Node/API/Query-revisions/revtoid.md create mode 100644 packages/docs/Node/API/Regtest-faucet/faucet.md create mode 100644 packages/docs/Node/API/Regtest-faucet/faucetScript.md create mode 100644 packages/docs/Node/API/Transaction/ancestors.md create mode 100644 packages/docs/Node/API/Transaction/bulk.md create mode 100644 packages/docs/Node/API/Transaction/json.md create mode 100644 packages/docs/Node/API/Transaction/post.md create mode 100644 packages/docs/Node/API/Wallet/balance.md create mode 100644 packages/docs/Node/API/Wallet/list-txs.md create mode 100644 packages/docs/Node/API/Wallet/received-outputs.md create mode 100644 packages/docs/Node/API/Wallet/sent-outputs.md create mode 100644 packages/docs/Node/API/Wallet/utxos.md create mode 100644 packages/docs/Node/API/api.md create mode 100644 packages/docs/Node/node.md delete mode 100644 packages/docs/node.md diff --git a/packages/docs/Node/API/Blockchain/height.md b/packages/docs/Node/API/Blockchain/height.md new file mode 100644 index 000000000..dc9e334ac --- /dev/null +++ b/packages/docs/Node/API/Blockchain/height.md @@ -0,0 +1,13 @@ +# height + +#### `/v1/CHAIN/NETWORK/:id/height` + +Get the height of an specific block. The `id` can be `best` or a block given hash. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/best/height +``` + +```json +{ "height": 101 } +``` diff --git a/packages/docs/Node/API/Blockchain/mine.md b/packages/docs/Node/API/Blockchain/mine.md new file mode 100644 index 000000000..f29966c20 --- /dev/null +++ b/packages/docs/Node/API/Blockchain/mine.md @@ -0,0 +1,13 @@ +# mine + +#### `/v1/CHAIN/NETWORK/mine` + +Mine an specific number of blocks to a random address. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/mine?count=1 +``` + +```json +{ "success": true } +``` diff --git a/packages/docs/Node/API/Blockchain/rpc.md b/packages/docs/Node/API/Blockchain/rpc.md new file mode 100644 index 000000000..65be082c8 --- /dev/null +++ b/packages/docs/Node/API/Blockchain/rpc.md @@ -0,0 +1,33 @@ +# rpc + +#### `/v1/CHAIN/NETWORK/rpc` + +Call a Bitcoin RPC method. + +```shell +curl -X POST http://localhost:1031/v1/LTC/regtest/rpc \ + -H "Content-Type: application/json" \ + -d '{ + "method": "getmempoolinfo", + "params": "" + }' +``` + +```json +{ + "result": { + "result": { + "loaded": true, + "size": 1, + "bytes": 144, + "usage": 1296, + "maxmempool": 300000000, + "mempoolminfee": 0.00001, + "minrelaytxfee": 0.00001, + "unbroadcastcount": 1 + }, + "error": null, + "id": 40795 + } +} +``` diff --git a/packages/docs/Node/API/Offchain/id.md b/packages/docs/Node/API/Offchain/id.md new file mode 100644 index 000000000..f52d49d3b --- /dev/null +++ b/packages/docs/Node/API/Offchain/id.md @@ -0,0 +1,27 @@ +# id + +#### `/v1/store/:id` + +Get the data stored in the offchain storage. + +```shell +curl -X GET http://localhost:1031/v1/store/fcdb882a0b9556a0c6fb2a89efe0633f0c256f24696f465d386a91803838e79a +``` + +```json +{ + "exp": "class A extends Contract { + constructor(n, url){ + super({ + n: n, + _url: url + }); + + } + } + new A(0.2815266905953051,'http://localhost:1031')", + "env":{}, + "mod":"", + "v":"0.24.0-beta.0" +} +``` diff --git a/packages/docs/Node/API/Offchain/store.md b/packages/docs/Node/API/Offchain/store.md new file mode 100644 index 000000000..0f2ecfd34 --- /dev/null +++ b/packages/docs/Node/API/Offchain/store.md @@ -0,0 +1,13 @@ +# store + +#### `/v1/store` + +Stores the hex of the data in the offchain storage. + +```shell +curl -X POST http://localhost:1031/v1/store \ + -H "Content-Type: application/json" \ + -d '{ + "data": "{\"exp\":\"3+1\"}" + }' +``` diff --git a/packages/docs/Node/API/Query-revisions/next.md b/packages/docs/Node/API/Query-revisions/next.md new file mode 100644 index 000000000..80627dbe1 --- /dev/null +++ b/packages/docs/Node/API/Query-revisions/next.md @@ -0,0 +1,13 @@ +# next + +#### `/v1/CHAIN/NETWORK/next/:rev` + +Get the next revision of a given revision. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/next/032fc7a37e7848f5fb2beb79f773631c6047be0a2e9a699e1355aa8d1c64155e:0 +``` + +```json +{ "rev": "44a1e658be5b1fa7b13511979c91497cacf9286aac694bbb75188b875384db98:0" } +``` diff --git a/packages/docs/Node/API/Query-revisions/non-standard-utxos.md b/packages/docs/Node/API/Query-revisions/non-standard-utxos.md new file mode 100644 index 000000000..0f620e278 --- /dev/null +++ b/packages/docs/Node/API/Query-revisions/non-standard-utxos.md @@ -0,0 +1,25 @@ +# non-standard-utxos + +#### `/v1/CHAIN/NETWORK/non-standard-utxos` + +Query revisions by module specifier, public key, limit, order, offset and list of transaction ids. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/non-standard-utxos?mod=1 +curl -X GET http://localhost:1031/v1/LTC/regtest/non-standard-utxos?publicKey=02e3b0... +curl -X GET http://localhost:1031/v1/LTC/regtest/non-standard-utxos?limit=10 +curl -X GET http://localhost:1031/v1/LTC/regtest/non-standard-utxos?order=DESC +curl -X GET http://localhost:1031/v1/LTC/regtest/non-standard-utxos?offset=10 + +id="4446faf2ea02713580152f2355bc91e2eac3649c85e38d882e1ca795bb7b1494:0" +json_array=$(jq -n --arg id "$id" '[$id]') +encoded_json=$(echo "$json_array" | jq -r @uri) +url="http://localhost:1031/v1/LTC/regtest/non-standard-utxos?ids=$encoded_json" +curl -X GET "$url" +``` + + + +```json +["4446faf2ea02713580152f2355bc91e2eac3649c85e38d882e1ca795bb7b1494:0"] +``` diff --git a/packages/docs/Node/API/Query-revisions/prev.md b/packages/docs/Node/API/Query-revisions/prev.md new file mode 100644 index 000000000..362c3b948 --- /dev/null +++ b/packages/docs/Node/API/Query-revisions/prev.md @@ -0,0 +1,13 @@ +# prev + +#### `/v1/CHAIN/NETWORK/prev/:rev` + +Get the previous revision of a given revision. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/prev/44a1e658be5b1fa7b13511979c91497cacf9286aac694bbb75188b875384db98:0 +``` + +```json +{ "rev": "032fc7a37e7848f5fb2beb79f773631c6047be0a2e9a699e1355aa8d1c64155e:0" } +``` diff --git a/packages/docs/Node/API/Query-revisions/revs.md b/packages/docs/Node/API/Query-revisions/revs.md new file mode 100644 index 000000000..90f00832a --- /dev/null +++ b/packages/docs/Node/API/Query-revisions/revs.md @@ -0,0 +1,23 @@ +# revs + +#### `/v1/CHAIN/NETWORK/revs` + +Get the revisions of a list of transactions. + +```shell +curl -X POST http://localhost:1031/v1/LTC/regtest/revs \ + -H "Content-Type: application/json" \ + -d '{ + "ids": [ + "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89", + "9343ce7ca5e2039ab5329b2918319bd1656983cf2e8f8de7c4001d61870d0eb8" + ] + }' +``` + +```json +[ + "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89", + "db98c59f328bb45b14a957ce44546f5bfe2f1bf4394de18e98f32188e76082be" +] +``` diff --git a/packages/docs/Node/API/Query-revisions/revtoid.md b/packages/docs/Node/API/Query-revisions/revtoid.md new file mode 100644 index 000000000..9b85c76b2 --- /dev/null +++ b/packages/docs/Node/API/Query-revisions/revtoid.md @@ -0,0 +1,17 @@ +# revToId + +#### `/v1/CHAIN/NETWORK/rev/:revToId` + +Given a revision, returns the id of the smart contract. + +```shell +curl -X POST http://localhost:1031/v1/LTC/regtest/revToId \ + -H "Content-Type: application/json" \ + -d '{ + "rev": "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89:0" + }' +``` + +```json +"db98c59f328bb45b14a957ce44546f5bfe2f1bf4394de18e98f32188e76082be:0" +``` diff --git a/packages/docs/Node/API/Regtest-faucet/faucet.md b/packages/docs/Node/API/Regtest-faucet/faucet.md new file mode 100644 index 000000000..2d09902af --- /dev/null +++ b/packages/docs/Node/API/Regtest-faucet/faucet.md @@ -0,0 +1,23 @@ +# faucet + +#### `/v1/CHAIN/NETWORK/faucet` + +Send coins to an address. + +```shell +curl -X POST http://localhost:1031/v1/LTC/regtest/faucet \ + -H "Content-Type: application/json" \ + -d '{ + "address": "mkMUZNoiLh4uuuENU5HNZ4Ssxo8BqEQc5t", + "value": "100000000" + }' +``` + +```json +{ + "txId": "68ef61b6c8896c42f983a0a80caa299ba8cfb0d9d03431ee5bcd6fbf7e0aa21b", + "vout": 0, + "height": -1, + "satoshis": "100000000" +} +``` diff --git a/packages/docs/Node/API/Regtest-faucet/faucetScript.md b/packages/docs/Node/API/Regtest-faucet/faucetScript.md new file mode 100644 index 000000000..e5be9485c --- /dev/null +++ b/packages/docs/Node/API/Regtest-faucet/faucetScript.md @@ -0,0 +1,23 @@ +# faucetScript + +#### `v1/CHAIN/NETWORK/faucetScript` + +Send coins to a script. + +```shell +curl -X POST http://localhost:1031/v1/LTC/regtest/faucetScript \ + -H "Content-Type: application/json" \ + -d '{ + "script": "76a914f7f1", + "value": "100000000" + }' +``` + +```json +{ + "txId": "68ef61b6c8896c42f983a0a80caa299ba8cfb0d9d03431ee5bcd6fbf7e0aa21b", + "vout": 0, + "height": -1, + "satoshis": "100000000" +} +``` diff --git a/packages/docs/Node/API/Transaction/ancestors.md b/packages/docs/Node/API/Transaction/ancestors.md new file mode 100644 index 000000000..aaac19a67 --- /dev/null +++ b/packages/docs/Node/API/Transaction/ancestors.md @@ -0,0 +1,17 @@ +# ancestors + +#### `/v1/CHAIN/NETWORK/tx/:txId/ancestors` + +Returns an array with the transaction IDs of the ancestors of a given transaction. An ancestor is a transaction that is an input to the given transaction. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/tx/e53c1440f547b51343d46a2acaafe127e915c7ed08a7ef2ed0ffc248360c0cca/ancestors +``` + +```json +[ + "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89", + "9343ce7ca5e2039ab5329b2918319bd1656983cf2e8f8de7c4001d61870d0eb8", + "db98c59f328bb45b14a957ce44546f5bfe2f1bf4394de18e98f32188e76082be" +] +``` diff --git a/packages/docs/Node/API/Transaction/bulk.md b/packages/docs/Node/API/Transaction/bulk.md new file mode 100644 index 000000000..13f9466d4 --- /dev/null +++ b/packages/docs/Node/API/Transaction/bulk.md @@ -0,0 +1,21 @@ +# bulk + +#### `/v1/CHAIN/NETWORK/tx/bulk` + +Returns the raw transaction hexes for a given list of transaction IDs. + +```shell +curl -X POST http://localhost:1031/v1/LTC/regtest/tx/bulk \ + -H "Content-Type: application/json" \ + -d '{ + "txIds": [ + "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89", + "9343ce7ca5e2039ab5329b2918319bd1656983cf2e8f8de7c4001d61870d0eb8", + "db98c59f328bb45b14a957ce44546f5bfe2f1bf4394de18e98f32188e76082be" + ] + }' +``` + +```json +["0100000002b80e0d87611d...", "0100000001b80e0d87611d...", "0100000000012b087e1832..."] +``` diff --git a/packages/docs/Node/API/Transaction/json.md b/packages/docs/Node/API/Transaction/json.md new file mode 100644 index 000000000..69869da51 --- /dev/null +++ b/packages/docs/Node/API/Transaction/json.md @@ -0,0 +1,39 @@ +# json + +#### `/v1/CHAIN/NETWORK/tx/:txId/json` + +Returns the JSON representation of a given transaction. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/tx/e53c1440f547b51343d46a2acaafe127e915c7ed08a7ef2ed0ffc248360c0cca/json +``` + +```json +{ + "txId": "e53c1440f547b51343d46a2acaafe127e915c7ed08a7ef2ed0ffc248360c0cca", + "txHex": "0100000001202aabc...", + "vsize": 443, + "version": 1, + "locktime": 0, + "ins": [ + { + "txId": "7c2f4dacaeac0a69c451bdd19f6c31d54def13b76ec8687160468d0ac8ab2a20", + "vout": 0, + "script": "47304402203...", + "sequence": 4294967295 + } + ], + "outs": [ + { + "address": "mryiaVyu9cDrdYCGzt8TimdxXPS1vmJS1a", + "script": "512102ff3...", + "value": 5820 + }, + { + "address": "mryiaVyu9cDrdYCGzt8TimdxXPS1vmJS1a", + "script": "76a9147db...", + "value": 99971398 + } + ] +} +``` diff --git a/packages/docs/Node/API/Transaction/post.md b/packages/docs/Node/API/Transaction/post.md new file mode 100644 index 000000000..1ed75b7a6 --- /dev/null +++ b/packages/docs/Node/API/Transaction/post.md @@ -0,0 +1,17 @@ +# post + +#### `/v1/CHAIN/NETWORK/tx/post` + +Posts a raw transaction to the network and returns its transaction ID. + +```shell +curl -X POST http://localhost:1031/v1/LTC/regtest/tx/post \ + -H "Content-Type: application/json" \ + -d '{ + "hex": "0100000002b80e0d87611d00c4..." + }' +``` + +```json +"e53c1440f547b51343d46a2acaafe127e915c7ed08a7ef2ed0ffc248360c0cca" +``` diff --git a/packages/docs/Node/API/Wallet/balance.md b/packages/docs/Node/API/Wallet/balance.md new file mode 100644 index 000000000..41a91eb1d --- /dev/null +++ b/packages/docs/Node/API/Wallet/balance.md @@ -0,0 +1,17 @@ +# balance + +#### `/v1/CHAIN/NETWORK/address/:address/balance` + +Returns the confirmed, unconfirmed and total balance for a given address. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/address/mkMUZNoiLh4uuuENU5HNZ4Ssxo8BqEQc5t/balance +``` + +```json +{ + "confirmed": 99927794, + "unconfirmed": 0, + "balance": 99927794 +} +``` diff --git a/packages/docs/Node/API/Wallet/list-txs.md b/packages/docs/Node/API/Wallet/list-txs.md new file mode 100644 index 000000000..6ba030deb --- /dev/null +++ b/packages/docs/Node/API/Wallet/list-txs.md @@ -0,0 +1,36 @@ +# list-txs + +#### `/v1/CHAIN/NETWORK/wallet/:address/list-txs` + +Returns the sent and received transactions for a given address. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/wallet/mkMUZNoiLh4uuuENU5HNZ4Ssxo8BqEQc5t/list-txs +``` + +```json +{ + "sentTxs": [ + { + "txId": "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89", + "inputsSatoshis": 99944756, + "outputsSatoshis": 99927794, + "satoshis": 16962 + }, + { + "txId": "9343ce7ca5e2039ab5329b2918319bd1656983cf2e8f8de7c4001d61870d0eb8", + "inputsSatoshis": 99961718, + "outputsSatoshis": 99944756, + "satoshis": 16962 + } + ], + "receivedTxs": [ + { + "txId": "db98c59f328bb45b14a957ce44546f5bfe2f1bf4394de18e98f32188e76082be", + "inputsSatoshis": 0, + "outputsSatoshis": 99961718, + "satoshis": 99961718 + } + ] +} +``` diff --git a/packages/docs/Node/API/Wallet/received-outputs.md b/packages/docs/Node/API/Wallet/received-outputs.md new file mode 100644 index 000000000..7deb65da9 --- /dev/null +++ b/packages/docs/Node/API/Wallet/received-outputs.md @@ -0,0 +1,26 @@ +# received-outputs + +#### `/v1/CHAIN/NETWORK/wallet/:address/received-outputs` + +Returns the outputs that were received by a given address. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/wallet/mkMUZNoiLh4uuuENU5HNZ4Ssxo8BqEQc5t/received-outputs +``` + +```json +[ + { + "output": "db98c59f328bb45b14a957ce44546f5bfe2f1bf4394de18e98f32188e76082be:5", + "amount": 99961718 + }, + { + "output": "9343ce7ca5e2039ab5329b2918319bd1656983cf2e8f8de7c4001d61870d0eb8:3", + "amount": 99944756 + }, + { + "output": "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89:3", + "amount": 99927794 + } +] +``` diff --git a/packages/docs/Node/API/Wallet/sent-outputs.md b/packages/docs/Node/API/Wallet/sent-outputs.md new file mode 100644 index 000000000..1fb6a6907 --- /dev/null +++ b/packages/docs/Node/API/Wallet/sent-outputs.md @@ -0,0 +1,22 @@ +# sent-outputs + +#### `/v1/CHAIN/NETWORK/wallet/:address/sent-outputs` + +Returns the outputs that were sent from a given address. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/wallet/mkMUZNoiLh4uuuENU5HNZ4Ssxo8BqEQc5t/sent-outputs +``` + +```json +[ + { + "output": "9343ce7ca5e2039ab5329b2918319bd1656983cf2e8f8de7c4001d61870d0eb8:1", + "amount": 99961718 + }, + { + "output": "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89:1", + "amount": 99944756 + } +] +``` diff --git a/packages/docs/Node/API/Wallet/utxos.md b/packages/docs/Node/API/Wallet/utxos.md new file mode 100644 index 000000000..96c23b1a8 --- /dev/null +++ b/packages/docs/Node/API/Wallet/utxos.md @@ -0,0 +1,22 @@ +# utxos + +#### `/v1/CHAIN/NETWORK/wallet/:address/utxos` + +Returns the UTXOs for a given address. + +```shell +curl -X GET http://localhost:1031/v1/LTC/regtest/wallet/mwJn1YPMq7y5F8J3LkC5Hxg9PHyZ5K4cFv/utxos +``` + +```json +[ + { + "address": "mkMUZNoiLh4uuuENU5HNZ4Ssxo8BqEQc5t", + "satoshis": 99927794, + "asm": "OP_DUP OP_HASH160 350dbb89c08f5b4aa19eb2bc0b4bb8ba5b79a873 OP_EQUALVERIFY OP_CHECKSIG", + "rev": "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89:3", + "txId": "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89", + "vout": 3 + } +] +``` diff --git a/packages/docs/Node/API/api.md b/packages/docs/Node/API/api.md new file mode 100644 index 000000000..a3ab4828a --- /dev/null +++ b/packages/docs/Node/API/api.md @@ -0,0 +1,59 @@ +The Bitcoin Computer Node exposes an API that can be used to interact with the node. +The variables `CHAIN` and `NETWORK` are used to define the chain and network that the node is running on. + +#### Wallet + +{.compact} +| Method | Description | +|-------------------------------------|----------------------------------------------------| +| [balance](./wallet/balance.md) | Get the balance of a wallet. | +| [list-txs](./Wallet/list-txs.md) | List sent and received transactions for a given address. | +| [sent-outputs](./Wallet/sent-outputs.md) | List sent outputs of a wallet. | +| [received-outputs](./Wallet/received-outputs.md) | List received outputs of a wallet. | +| [utxos](./Wallet/utxos.md) | List unspent outputs of a wallet. | + +#### Transactions + +{.compact} +| Method | Description | +|-------------------------------------|----------------------------------------------------| +| [ancestors](./Transaction/ancestors.md) | Get the ancestors of a transaction. | +| [bulk](./Transaction/bulk.md) | Get raw transactions for a list of transaction ids. | +| [json](./Transaction/json.md) | Get a transaction in json format. | +| [post](./Transaction/post.md) | Post a transaction to the Bitcoin network. | + +#### Blockchain + +{.compact} +| Method | Description | +|-------------------------------------|----------------------------------------------------| +| [height](./Blockchain/height.md) | Get the height of an specific block. | +| [mine](./Blockchain/mine.md) | Mine an specific number of blocks to a random address. | +| [rpc](./Blockchain/height.md) | Call a Bitcoin RPC method. | + +#### Regtest Faucet + +{.compact} +| Method | Description | +|-------------------------------------|----------------------------------------------------| +| [faucet](./Regtest-faucet/faucet.md) | Get coins from the faucet. | +| [faucetScript](./Regtest-faucet/faucetScript.md) | Get coins from the faucet using a script. | + +#### Query revisions + +{.compact} +| Method | Description | +|-------------------------------------|----------------------------------------------------| +| [next](./Query-revisions/next.md) | Get the next revision of a given revision. | +| [prev](./Query-revisions/prev.md) | Get the previous revision of a given revision. | +| [non-standard-utxos](./Query-revisions/non-standard-utxos.md) | Query revisions by module specifier, public key, limit, order, offset and list of transaction ids. | +| [revs](./Query-revisions/revs.md) | Get the revisions of a list of transactions. | +| [revToId](./Query-revisions/revtoid.md) | Given a revision, get the id of the smart contract. | + +#### OffChain + +{.compact} +| Method | Description | +|-------------------------------------|----------------------------------------------------| +| [id](./Regtest-faucet/faucet.md) | Get the data stored in the offchain storage. | +| [store](./Regtest-faucet/faucetScript.md) | Stores the hex of the data in the offchain storage. | diff --git a/packages/docs/Node/node.md b/packages/docs/Node/node.md new file mode 100644 index 000000000..e1fc0a919 --- /dev/null +++ b/packages/docs/Node/node.md @@ -0,0 +1,284 @@ +--- +order: -60 +--- + +# Node + +## Prerequisites + +You need to have [git](https://www.git-scm.com/), [node.js](https://nodejs.org/) and [docker](https://www.docker.com/) installed. + +## Installation + + + +```sh +# Download the monorepo +git clone https://github.com/bitcoin-computer/monorepo.git + +# Move into monorepo folder +cd monorepo + +# Install the dependencies +npm install + +``` + + + +## Usage + +### Start the Node + +To start your node at `http://localhost:1031` run the commands below. The node is ready once the log activity subsides. On regtest this will take a few minutes, on mainnet and testnet it can take days or even weeks, depending on your hardware. + + + +```sh +# Move to node folder +cd packages/node + +# Copy the .env file and litecoin.conf file from the examples +cp chain-setup/ltc/regtest/.env.example .env +cp chain-setup/ltc/regtest/litecoin.conf.example litecoin.conf + +# Run the node on litecoin regtest +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. + + + +```sh +npm run test +``` + + + +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 + +In regtest mode, you can fund a wallet with the following commands. + + + +```sh +# Fund Litecoin regtest wallet +npm run fund ltc ... + +# Fund Bitcoin regtest wallet +npm run fund btc ... +``` + + + +### Stop the Node + +You can stop the node with the command below. When you restart the process, it will resume from the last block processed. + + + +```sh +npm run down +``` + + + +### Reset the Node + +The command below will reset the database, delete all blockchain data, and stop all docker containers. + + + +```sh +npm run clean +``` + + + +### Client Side Library + +The [Bitcoin Computer Library](https://github.com/bitcoin-computer/monorepo/tree/main/packages/lib#readme) can connect to a Bitcoin Computer Node to provides access to its functionality. + + + +```js +// Import client side library +import { Computer } from '@bitcoin-computer/lib' + +// Configuration to connect to node on localhost +const conf = { + chain: 'LTC', + network: 'regtest', + url: 'http://localhost:1031', +} + +// Create instance of client side library +const computer = new Computer(conf) +const address = computer.getAddress() + +// Fund client side library +const { txId, vout } = await computer.faucet(1e4) + +// Return the utxos +expect(await new Computer(conf).getUtxos(address)).deep.eq([`${txId}:${vout}`]) + +// Return the balance +expect(await new Computer(conf).getBalance(address).balance).eq(1e4) + +// Return the transactions +expect(await new Computer(conf).listTxs(address)).deep.eq({ + sentTxs: [], + receivedTxs: [ + { + txId, + inputsSatoshis: 0, + outputsSatoshis: 1e4, + satoshis: 1e4, + }, + ], +}) +``` + + + +If you do not specify a `url` property it will default to the url below. The node at that url runs Litecoin on regtest network mode and uses the latest version of the Bitcoin Computer Node software. + +``` +https://rltc.node.bitcoincomputer.io +``` + +## Configuration + +You can configure several options by editing the `.env` file. + + + +```bash +# Chain: BTC, LTC, DOGE or PEPE +BCN_CHAIN='LTC' +# Network: mainnet, testnet, or regtest +BCN_NETWORK='regtest' + +# Postgres Connection Credentials +POSTGRES_USER='bcn' +POSTGRES_PASSWORD='bcn' +POSTGRES_DB='bcn' +POSTGRES_HOST='db' +POSTGRES_PORT='5432' +POSTGRES_MAX_CONNECTIONS='20' +POSTGRES_IDLE_TIMEOUT_MILLIS='3000' + +# Bitcoin Node Settings +BITCOIN_IMAGE='litecoinproject/litecoin-core:0.21' +BITCOIN_DATA_DIR='/home/litecoin/.litecoin' +BITCOIN_CONF_FILE='litecoin.conf' + +# Node Settings +# RPC Client Credentials +BITCOIN_RPC_USER='bcn-admin' +BITCOIN_RPC_PASSWORD='kH4nU5Okm6-uyC0_mA5ztVNacJqZbYd_KGLl6mx722A=' +BITCOIN_RPC_HOST='node' +BITCOIN_RPC_PORT='19332' +BITCOIN_P2P_PORT='19444' +BITCOIN_RPC_PROTOCOL='http' + +# Default wallet name +BITCOIN_DEFAULT_WALLET='defaultwallet' + +# Bitcoin Computer Node (BCN) Settings +# Port for Bitcoin Computer Node +BCN_PORT='1031' + +# Enable to launch with fixed number of parallel workers +# BCN_NUM_WORKERS='6' + +BCN_ZMQ_URL='tcp://node:28332' +BCN_ZMQ_PORT='28332' +# Height of the block at which the zmq connection should start +BCN_ZMQ_ACTIVATION_HEIGHT=1 + +# Url of the Bitcoin Computer Node, defaults to localhost +BCN_URL='http://127.0.0.1:1031' + +# Allowed RPC Methods +BCN_ALLOWED_RPC_METHODS='^get|^gen|^send|^lis' + +# Setup the environment to 'prod' (no console logs) or 'dev' +BCN_ENV='dev' + +# Winston Logger Settings +# Log levels +# 0: Error logs only +# 1: Error and warning logs +# 2: Error, warning and info logs +# 3: Error, warning, info and http logs +# 4: Error, warning, info, http and debug logs +BCN_LOG_LEVEL='2' +# Maximum number of logs to keep. If not set, no logs will be removed. This can be +# a number of files or number of days. If using days, add 'd' as the suffix. +BCN_LOG_MAX_FILES='14d' +# Maximum log file size. You can use 'k' for KB, 'm' for MB, and 'g' for GB. Once +# the size of the log file exceeds the specified size, the log is rotated. If no +# size is specified the log is not rotated. +BCN_LOG_MAX_SIZE='20m' +# A boolean to define whether or not to gzip archived log files. +BCN_LOG_ZIP='false' + +# Show logs at db service +BCN_SHOW_DB_LOGS='false' + +# Rate Limiting Settings +BCN_RATE_LIMIT_ENABLED='false' +BCN_RATE_LIMIT_WINDOW='900000' +BCN_RATE_LIMIT_MAX='300' +BCN_RATE_LIMIT_STANDARD_HEADERS='true' +BCN_RATE_LIMIT_LEGACY_HEADERS='false' + +# Comma separated list of banned countries, encoded as ISO-3166 alpha2 country. +# codes (see https://www.geonames.org/countries/) +BCN_BANNED_COUNTRIES= + +# Default value for protocol in the _url parameter. Set to https if behind a load balancer. +BCN_OFFCHAIN_PROTOCOL= +``` + + + + + +## Versioning + +If you run your own node, make sure to use the same versions of Lib and Node. diff --git a/packages/docs/node.md b/packages/docs/node.md deleted file mode 100644 index 88fffbde2..000000000 --- a/packages/docs/node.md +++ /dev/null @@ -1,737 +0,0 @@ ---- -order: -60 ---- - -# Node - -## Prerequisites - -You need to have [git](https://www.git-scm.com/), [node.js](https://nodejs.org/) and [docker](https://www.docker.com/) installed. - -## Installation - - - -```sh -# Download the monorepo -git clone https://github.com/bitcoin-computer/monorepo.git - -# Move into monorepo folder -cd monorepo - -# Install the dependencies -npm install - -# Build the docker image -npm run build:node -``` - - - -## Usage - -### Start the Node - -To start your node at `http://localhost:1031` run the commands below. The node is ready once the log activity subsides. On regtest this will take a few minutes, on mainnet and testnet it can take days or even weeks, depending on your hardware. - - - -```sh -# Move to node folder -cd packages/node - -# Copy the .env file and litecoin.conf file from the examples -cp chain-setup/ltc/regtest/.env.example .env -cp chain-setup/ltc/regtest/litecoin.conf.example litecoin.conf - -# Run the node on litecoin regtest -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. - - - -```sh -npm run test -``` - - - -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 - -In regtest mode, you can fund a wallet with the following commands. - - - -```sh -# Fund Litecoin regtest wallet -npm run fund ltc ... - -# Fund Bitcoin regtest wallet -npm run fund btc ... -``` - - - -### Stop the Node - -You can stop the node with the command below. When you restart the process, it will resume from the last block processed. - - - -```sh -npm run down -``` - - - -### Reset the Node - -The command below will reset the database, delete all blockchain data, and stop all docker containers. - - - -```sh -npm run clean -``` - - - -### Client Side Library - -The [Bitcoin Computer Library](https://github.com/bitcoin-computer/monorepo/tree/main/packages/lib#readme) can connect to a Bitcoin Computer Node to provides access to its functionality. - - - -```js -// Import client side library -import { Computer } from "@bitcoin-computer/lib"; - -// Configuration to connect to node on localhost -const conf = { - chain: "LTC", - network: "regtest", - url: "http://localhost:1031", -}; - -// Create instance of client side library -const computer = new Computer(conf); -const address = computer.getAddress(); - -// Fund client side library -const { txId, vout } = await computer.faucet(1e4); - -// Return the utxos -expect(await new Computer(conf).getUtxos(address)).deep.eq([`${txId}:${vout}`]); - -// Return the balance -expect(await new Computer(conf).getBalance(address).balance).eq(1e4); - -// Return the transactions -expect(await new Computer(conf).listTxs(address)).deep.eq({ - sentTxs: [], - receivedTxs: [ - { - txId, - inputsSatoshis: 0, - outputsSatoshis: 1e4, - satoshis: 1e4, - }, - ], -}); -``` - - - -If you do not specify a `url` property it will default to the url below. The node at that url runs Litecoin on regtest network mode and uses the latest version of the Bitcoin Computer Node software. - -``` -https://rltc.node.bitcoincomputer.io -``` - -## Configuration - -You can configure several options by editing the `.env` file. - - - -```bash -# Chain: BTC, LTC, DOGE or PEPE -BCN_CHAIN='LTC' -# Network: mainnet, testnet, or regtest -BCN_NETWORK='regtest' - -# Postgres Connection Credentials -POSTGRES_USER='bcn' -POSTGRES_PASSWORD='bcn' -POSTGRES_DB='bcn' -POSTGRES_HOST='db' -POSTGRES_PORT='5432' -POSTGRES_MAX_CONNECTIONS='20' -POSTGRES_IDLE_TIMEOUT_MILLIS='3000' - -# Bitcoin Node Settings -BITCOIN_IMAGE='litecoinproject/litecoin-core:0.21' -BITCOIN_DATA_DIR='/home/litecoin/.litecoin' -BITCOIN_CONF_FILE='litecoin.conf' - -# Node Settings -# RPC Client Credentials -BITCOIN_RPC_USER='bcn-admin' -BITCOIN_RPC_PASSWORD='kH4nU5Okm6-uyC0_mA5ztVNacJqZbYd_KGLl6mx722A=' -BITCOIN_RPC_HOST='node' -BITCOIN_RPC_PORT='19332' -BITCOIN_P2P_PORT='19444' -BITCOIN_RPC_PROTOCOL='http' - -# Default wallet name -BITCOIN_DEFAULT_WALLET='defaultwallet' - -# Bitcoin Computer Node (BCN) Settings -# Port for Bitcoin Computer Node -BCN_PORT='1031' - -# Enable to launch with fixed number of parallel workers -# BCN_NUM_WORKERS='6' - -BCN_ZMQ_URL='tcp://node:28332' -BCN_ZMQ_PORT='28332' -# Height of the block at which the zmq connection should start -BCN_ZMQ_ACTIVATION_HEIGHT=1 - -# Url of the Bitcoin Computer Node, defaults to localhost -BCN_URL='http://127.0.0.1:1031' - -# Allowed RPC Methods -BCN_ALLOWED_RPC_METHODS='^get|^gen|^send|^lis' - -# Setup the environment to 'prod' (no console logs) or 'dev' -BCN_ENV='dev' - -# Winston Logger Settings -# Log levels -# 0: Error logs only -# 1: Error and warning logs -# 2: Error, warning and info logs -# 3: Error, warning, info and http logs -# 4: Error, warning, info, http and debug logs -BCN_LOG_LEVEL='2' -# Maximum number of logs to keep. If not set, no logs will be removed. This can be -# a number of files or number of days. If using days, add 'd' as the suffix. -BCN_LOG_MAX_FILES='14d' -# Maximum log file size. You can use 'k' for KB, 'm' for MB, and 'g' for GB. Once -# the size of the log file exceeds the specified size, the log is rotated. If no -# size is specified the log is not rotated. -BCN_LOG_MAX_SIZE='20m' -# A boolean to define whether or not to gzip archived log files. -BCN_LOG_ZIP='false' - -# Show logs at db service -BCN_SHOW_DB_LOGS='false' - -# Rate Limiting Settings -BCN_RATE_LIMIT_ENABLED='false' -BCN_RATE_LIMIT_WINDOW='900000' -BCN_RATE_LIMIT_MAX='300' -BCN_RATE_LIMIT_STANDARD_HEADERS='true' -BCN_RATE_LIMIT_LEGACY_HEADERS='false' - -# Comma separated list of banned countries, encoded as ISO-3166 alpha2 country. -# codes (see https://www.geonames.org/countries/) -BCN_BANNED_COUNTRIES= - -# Default value for protocol in the _url parameter. Set to https if behind a load balancer. -BCN_OFFCHAIN_PROTOCOL= -``` - - - - - -## Versioning - -If you run your own node, make sure to use the same versions of Lib and Node. - -## Api - -The Bitcoin Computer Node exposes an API that can be used to interact with the node. -The variables `CHAIN` and `NETWORK` are used to define the chain and network that the node is running on. - -### Wallet - -#### `/v1/CHAIN/NETWORK/wallet/:address/utxos` - -Returns the UTXOs for a given address. - -```shell -curl -X GET http://localhost:1031/v1/LTC/regtest/wallet/mwJn1YPMq7y5F8J3LkC5Hxg9PHyZ5K4cFv/utxos -``` - -```json -[ - { - "address": "mkMUZNoiLh4uuuENU5HNZ4Ssxo8BqEQc5t", - "satoshis": 99927794, - "asm": "OP_DUP OP_HASH160 350dbb89c08f5b4aa19eb2bc0b4bb8ba5b79a873 OP_EQUALVERIFY OP_CHECKSIG", - "rev": "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89:3", - "txId": "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89", - "vout": 3 - } -] -``` - -#### `/v1/CHAIN/NETWORK/address/:address/balance` - -Returns the confirmed, unconfirmed and total balance for a given address. - -```shell -curl -X GET http://localhost:1031/v1/LTC/regtest/address/mkMUZNoiLh4uuuENU5HNZ4Ssxo8BqEQc5t/balance -``` - -```json -{ - "confirmed": 99927794, - "unconfirmed": 0, - "balance": 99927794 -} -``` - -#### `/v1/CHAIN/NETWORK/wallet/:address/sent-outputs` - -Returns the outputs that were sent from a given address. - -```shell -curl -X GET http://localhost:1031/v1/LTC/regtest/wallet/mkMUZNoiLh4uuuENU5HNZ4Ssxo8BqEQc5t/sent-outputs -``` - -```json -[ - { - "output": "9343ce7ca5e2039ab5329b2918319bd1656983cf2e8f8de7c4001d61870d0eb8:1", - "amount": 99961718 - }, - { - "output": "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89:1", - "amount": 99944756 - } -] -``` - -#### `/v1/CHAIN/NETWORK/wallet/:address/received-outputs` - -Returns the outputs that were received by a given address. - -```shell -curl -X GET http://localhost:1031/v1/LTC/regtest/wallet/mkMUZNoiLh4uuuENU5HNZ4Ssxo8BqEQc5t/received-outputs -``` - -```json -[ - { - "output": "db98c59f328bb45b14a957ce44546f5bfe2f1bf4394de18e98f32188e76082be:5", - "amount": 99961718 - }, - { - "output": "9343ce7ca5e2039ab5329b2918319bd1656983cf2e8f8de7c4001d61870d0eb8:3", - "amount": 99944756 - }, - { - "output": "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89:3", - "amount": 99927794 - } -] -``` - -#### `/v1/CHAIN/NETWORK/wallet/:address/list-txs` - -Returns the sent and received transactions for a given address. - -```shell -curl -X GET http://localhost:1031/v1/LTC/regtest/wallet/mkMUZNoiLh4uuuENU5HNZ4Ssxo8BqEQc5t/list-txs -``` - -```json -{ - "sentTxs": [ - { - "txId": "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89", - "inputsSatoshis": 99944756, - "outputsSatoshis": 99927794, - "satoshis": 16962 - }, - { - "txId": "9343ce7ca5e2039ab5329b2918319bd1656983cf2e8f8de7c4001d61870d0eb8", - "inputsSatoshis": 99961718, - "outputsSatoshis": 99944756, - "satoshis": 16962 - } - ], - "receivedTxs": [ - { - "txId": "db98c59f328bb45b14a957ce44546f5bfe2f1bf4394de18e98f32188e76082be", - "inputsSatoshis": 0, - "outputsSatoshis": 99961718, - "satoshis": 99961718 - } - ] -} -``` - -### Transactions - -#### `/v1/CHAIN/NETWORK/tx/bulk` - -Returns the raw transaction for a given list of transaction IDs. - -```shell -curl -X POST http://localhost:1031/v1/LTC/regtest/tx/bulk \ - -H "Content-Type: application/json" \ - -d '{ - "txIds": [ - "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89", - "9343ce7ca5e2039ab5329b2918319bd1656983cf2e8f8de7c4001d61870d0eb8", - "db98c59f328bb45b14a957ce44546f5bfe2f1bf4394de18e98f32188e76082be" - ] - }' -``` - -```json -[ - "0100000002b80e0d87611d00c4...", - "0100000001b80e0d87611d00c4...", - "0100000000012b087e18328f98..." -] -``` - -#### `/v1/CHAIN/NETWORK/tx/post` - -Posts a raw transaction to the network. - -```shell -curl -X POST http://localhost:1031/v1/LTC/regtest/tx/post \ - -H "Content-Type: application/json" \ - -d '{ - "hex": "0100000002b80e0d87611d00c4..." - }' -``` - -```json -"e53c1440f547b51343d46a2acaafe127e915c7ed08a7ef2ed0ffc248360c0cca" -``` - -#### `/v1/CHAIN/NETWORK/tx/:txId/ancestors` - -Returns the ancestors of a given transaction. - -```shell -curl -X GET http://localhost:1031/v1/LTC/regtest/tx/e53c1440f547b51343d46a2acaafe127e915c7ed08a7ef2ed0ffc248360c0cca/ancestors -``` - -```json -[ - "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89", - "9343ce7ca5e2039ab5329b2918319bd1656983cf2e8f8de7c4001d61870d0eb8", - "db98c59f328bb45b14a957ce44546f5bfe2f1bf4394de18e98f32188e76082be" -] -``` - -#### `/v1/CHAIN/NETWORK/tx/:txId/json` - -Returns the JSON representation of a given transaction. - -```shell -curl -X GET http://localhost:1031/v1/LTC/regtest/tx/e53c1440f547b51343d46a2acaafe127e915c7ed08a7ef2ed0ffc248360c0cca/json -``` - -```json -{ - "txId": "e53c1440f547b51343d46a2acaafe127e915c7ed08a7ef2ed0ffc248360c0cca", - "txHex": "0100000001202aabc...", - "vsize": 443, - "version": 1, - "locktime": 0, - "ins": [ - { - "txId": "7c2f4dacaeac0a69c451bdd19f6c31d54def13b76ec8687160468d0ac8ab2a20", - "vout": 0, - "script": "47304402203...", - "sequence": 4294967295 - } - ], - "outs": [ - { - "address": "mryiaVyu9cDrdYCGzt8TimdxXPS1vmJS1a", - "script": "512102ff3...", - "value": 5820 - }, - { - "address": "mryiaVyu9cDrdYCGzt8TimdxXPS1vmJS1a", - "script": "76a9147db...", - "value": 99971398 - } - ] -} -``` - -### Blockchain - -#### `/v1/CHAIN/NETWORK/mine` - -Mine an specific number of blocks to a random address. - -```shell -curl -X GET http://localhost:1031/v1/LTC/regtest/mine?count=1 -``` - -```json -{ "success": true } -``` - -#### `/v1/CHAIN/NETWORK/:id/height` - -Get the height an specific block. The `id` can be `best` or a block given hash. - -```shell -curl -X GET http://localhost:1031/v1/LTC/regtest/best/height -``` - -```json -{ "height": 101 } -``` - -#### `/v1/CHAIN/NETWORK/rpc` - -Make a RPC call to the node. - -```shell -curl -X POST http://localhost:1031/v1/LTC/regtest/rpc \ - -H "Content-Type: application/json" \ - -d '{ - "method": "getmempoolinfo", - "params": "" - }' -``` - -```json -{ - "result": { - "result": { - "loaded": true, - "size": 1, - "bytes": 144, - "usage": 1296, - "maxmempool": 300000000, - "mempoolminfee": 0.00001, - "minrelaytxfee": 0.00001, - "unbroadcastcount": 1 - }, - "error": null, - "id": 40795 - } -} -``` - -### Regtest Faucet - -#### `/v1/CHAIN/NETWORK/faucet` - -Send coins to an address. - -```shell -curl -X POST http://localhost:1031/v1/LTC/regtest/faucet \ - -H "Content-Type: application/json" \ - -d '{ - "address": "mkMUZNoiLh4uuuENU5HNZ4Ssxo8BqEQc5t", - "value": "100000000" - }' -``` - -```json -{ - "txId": "68ef61b6c8896c42f983a0a80caa299ba8cfb0d9d03431ee5bcd6fbf7e0aa21b", - "vout": 0, - "height": -1, - "satoshis": "100000000" -} -``` - -#### `v1/CHAIN/NETWORK/faucetScript` - -Send coins to a script. - -```shell -curl -X POST http://localhost:1031/v1/LTC/regtest/faucetScript \ - -H "Content-Type: application/json" \ - -d '{ - "script": "76a914f7f1", - "value": "100000000" - }' -``` - -```json -{ - "txId": "68ef61b6c8896c42f983a0a80caa299ba8cfb0d9d03431ee5bcd6fbf7e0aa21b", - "vout": 0, - "height": -1, - "satoshis": "100000000" -} -``` - -### Query revisions - -#### `/v1/CHAIN/NETWORK/revs` - -Get the revisions of a list of transactions. - -```shell -curl -X POST http://localhost:1031/v1/LTC/regtest/revs \ - -H "Content-Type: application/json" \ - -d '{ - "ids": [ - "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89", - "9343ce7ca5e2039ab5329b2918319bd1656983cf2e8f8de7c4001d61870d0eb8" - ] - }' -``` - -```json -[ - "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89", - "db98c59f328bb45b14a957ce44546f5bfe2f1bf4394de18e98f32188e76082be" -] -``` - -#### `/v1/CHAIN/NETWORK/rev/:revToId` - -Given a revision, returns the id of the smart contract. - -```shell -curl -X POST http://localhost:1031/v1/LTC/regtest/revToId \ - -H "Content-Type: application/json" \ - -d '{ - "rev": "5a04f3cdb0450fd4708dfcd2fe86f51c6077add296507d69f2620c15e94c8e89:0" - }' -``` - -```json -"db98c59f328bb45b14a957ce44546f5bfe2f1bf4394de18e98f32188e76082be:0" -``` - -#### `/v1/CHAIN/NETWORK/next/:rev` - -Get the next revision of a given revision. - -```shell -curl -X GET http://localhost:1031/v1/LTC/regtest/next/032fc7a37e7848f5fb2beb79f773631c6047be0a2e9a699e1355aa8d1c64155e:0 -``` - -```json -{ "rev": "44a1e658be5b1fa7b13511979c91497cacf9286aac694bbb75188b875384db98:0" } -``` - -#### `/v1/CHAIN/NETWORK/prev/:rev` - -Get the previous revision of a given revision. - -```shell -curl -X GET http://localhost:1031/v1/LTC/regtest/prev/44a1e658be5b1fa7b13511979c91497cacf9286aac694bbb75188b875384db98:0 -``` - -```json -{ "rev": "032fc7a37e7848f5fb2beb79f773631c6047be0a2e9a699e1355aa8d1c64155e:0" } -``` - -#### `/v1/CHAIN/NETWORK/non-standard-utxos` - -Query revisions by module specifier, public key, limit, order, offset and list of transaction ids. - -```shell -curl -X GET http://localhost:1031/v1/LTC/regtest/non-standard-utxos?mod=1 -curl -X GET http://localhost:1031/v1/LTC/regtest/non-standard-utxos?publicKey=02e3b0... -curl -X GET http://localhost:1031/v1/LTC/regtest/non-standard-utxos?limit=10 -curl -X GET http://localhost:1031/v1/LTC/regtest/non-standard-utxos?order=DESC -curl -X GET http://localhost:1031/v1/LTC/regtest/non-standard-utxos?offset=10 - -id="4446faf2ea02713580152f2355bc91e2eac3649c85e38d882e1ca795bb7b1494:0" -json_array=$(jq -n --arg id "$id" '[$id]') -encoded_json=$(echo "$json_array" | jq -r @uri) -url="http://localhost:1031/v1/LTC/regtest/non-standard-utxos?ids=$encoded_json" -curl -X GET "$url" -``` - - - -```json -["4446faf2ea02713580152f2355bc91e2eac3649c85e38d882e1ca795bb7b1494:0"] -``` - -### OffChain - -#### `/v1/store/:id` - -Get the data stored in the offchain storage. - -```shell -curl -X GET http://localhost:1031/v1/store/fcdb882a0b9556a0c6fb2a89efe0633f0c256f24696f465d386a91803838e79a -``` - -```json -{ - "exp": "class A extends Contract { - constructor(n, url){ - super({ - n: n, - _url: url - }); - - } - } - new A(0.2815266905953051,'http://localhost:1031')", - "env":{}, - "mod":"", - "v":"0.24.0-beta.0" -} -``` - -#### `/v1/store` - -Stores the hex of the data in the offchain storage. - -```shell -curl -X POST http://localhost:1031/v1/store \ - -H "Content-Type: application/json" \ - -d '{ - "data": "{\"exp\":\"3+1\"}" - }' -``` From 113486755d7d37f913d48570ee92161b41ef7662 Mon Sep 17 00:00:00 2001 From: ltardivo Date: Fri, 14 Feb 2025 18:29:05 -0300 Subject: [PATCH 11/19] Adds links to vite template and nodeJs template --- packages/docs/start.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/docs/start.md b/packages/docs/start.md index 7f219f347..417fd758b 100644 --- a/packages/docs/start.md +++ b/packages/docs/start.md @@ -185,7 +185,7 @@ 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: +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 From 153dd1466bafd8dbfc4515f359c8c8c0924bce4d Mon Sep 17 00:00:00 2001 From: ltardivo Date: Fri, 14 Feb 2025 18:29:46 -0300 Subject: [PATCH 12/19] Adds basic description for setting non-standard scripts on _owner --- packages/docs/language.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/docs/language.md b/packages/docs/language.md index a729b904c..8ad80b8e1 100644 --- a/packages/docs/language.md +++ b/packages/docs/language.md @@ -70,7 +70,7 @@ Properties named `_amount`, `_owners`, `_readers`, and `_url` provide control ov ```ts type OutputDetails = { // determines which users can update the object - _owners?: string[] + _owners?: string[] | string // determines number of Satoshis stored in the output associated with the object _amount?: number @@ -86,7 +86,11 @@ type OutputDetails = { 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 `_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. From 31ec3b71bcac153df0c8c68e22382b87319b44c5 Mon Sep 17 00:00:00 2001 From: ltardivo Date: Fri, 14 Feb 2025 18:30:02 -0300 Subject: [PATCH 13/19] Adds Advanced topics to tutorial --- packages/docs/tutorial.md | 60 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 3 deletions(-) diff --git a/packages/docs/tutorial.md b/packages/docs/tutorial.md index 4a2ce7cd7..66574ec40 100644 --- a/packages/docs/tutorial.md +++ b/packages/docs/tutorial.md @@ -23,9 +23,9 @@ class Chat extends Contract { } ``` -=== :paperclip: **Smart Object** +!!!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/). @@ -150,7 +150,7 @@ 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. @@ -164,6 +164,8 @@ 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. @@ -246,3 +248,55 @@ await paymentB.cashOut() ``` 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. From 0dab8cf94134e08f063cf53d149c03caba4fbd7d Mon Sep 17 00:00:00 2001 From: ltardivo Date: Fri, 14 Feb 2025 18:30:34 -0300 Subject: [PATCH 14/19] Include table for function parameters on Lib API --- packages/docs/Lib/broadcast.md | 14 ++++++---- packages/docs/Lib/constructor.md | 30 ++++++++++---------- packages/docs/Lib/decode.md | 30 ++++++++++---------- packages/docs/Lib/deploy.md | 19 +++++++------ packages/docs/Lib/encode.md | 2 +- packages/docs/Lib/faucet.md | 17 +++++++----- packages/docs/Lib/fund.md | 26 ++++++++++-------- packages/docs/Lib/load.md | 16 +++++++---- packages/docs/Lib/new.md | 47 ++++++++++++++++---------------- packages/docs/Lib/rpcCall.md | 19 +++++++------ packages/docs/Lib/send.md | 18 +++++++----- packages/docs/Lib/sign.md | 22 +++++++++------ packages/docs/Lib/sync.md | 17 ++++++++---- 13 files changed, 158 insertions(+), 119 deletions(-) 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 \:\. +A string encoding the location where the module is stored. The format is \:\. ### Examples + ```ts -const revA = await computer.deploy( - `export class A extends Contract {}` -) +const revA = await computer.deploy(`export class A extends Contract {}`) const revB = await computer.deploy(` import { A } from '${revA}' @@ -46,4 +49,4 @@ const tx = await computer.encode(transition) !!!secondary Previously this function was called `export` but this name is deprecated since version 0.16.0. -!!! \ No newline at end of file +!!! diff --git a/packages/docs/Lib/encode.md b/packages/docs/Lib/encode.md index 5c39dd2ed..c0266e89f 100644 --- a/packages/docs/Lib/encode.md +++ b/packages/docs/Lib/encode.md @@ -86,7 +86,7 @@ It returns an object `{ tx, effect }` where `tx` is a Bitcoin transaction and `e { tx: BitcoinLib.Transaction, effect: { res: Json; env: Json } } ``` -The transaction `tx` is an object from the [NakamotoJS](https://github.com/bitcoin-computer/monorepo/tree/main/packages/nakamotojs#nakamotojs-nakamotojs) library - a [BitcoinJS](https://github.com/bitcoinjs/bitcoinjs-lib?tab=readme-ov-file#bitcoinjs-bitcoinjs-lib) clone that supports LTC and BTC and has some extra features that make is easier to build advanced applications like exchanges. +The transaction `tx` is an object from the [NakamotoJS](https://github.com/bitcoin-computer/monorepo/tree/main/packages/nakamotojs#nakamotojs-nakamotojs) library - a [BitcoinJS](https://github.com/bitcoinjs/bitcoinjs-lib?tab=readme-ov-file#bitcoinjs-bitcoinjs-lib) clone that supports LTC, BTC, PEPE and DOGE, and has some extra features that make is easier to build advanced applications like exchanges. The `res` object contains the result of the evaluation. diff --git a/packages/docs/Lib/faucet.md b/packages/docs/Lib/faucet.md index 2db22c273..2b36b7063 100644 --- a/packages/docs/Lib/faucet.md +++ b/packages/docs/Lib/faucet.md @@ -3,11 +3,13 @@ The `faucet` function funds a computer object. It is only available when the computer object is connected to a node in regtest mode. The faucet function creates a utxo to fund the address. The utxo is created with the amount of satoshis specified in the first parameter. The address to be funded can be specified in the second parameter. If the address is not specified, the address of the computer object is used. The transaction is broadcasted to the network, and a block is mined immediately to confirm the transaction. ### Type + ```ts -(amount: number, address = this.getAddress()) => Promise<_Unspent> +;(amount: number, address = this.getAddress()) => Promise<_Unspent> ``` ### Syntax + ```js const utxo = await computer.broadcast(amount) const utxo = await computer.broadcast(amount, address) @@ -15,18 +17,19 @@ const utxo = await computer.broadcast(amount, address) ### Parameters -#### amount -An amount of Satoshi - -#### address -An string encoded address to be funded +{.compact} +| Parameter | Description | +|--------------|---------------------------------------------------------------| +| amount | An amount of Satoshi | +| address | An string encoded address to be funded | ### Return value The utxo created to fund the address. ### Examples + ```ts const computer = new Computer() await computer.faucet(0.001e8) -``` \ No newline at end of file +``` diff --git a/packages/docs/Lib/fund.md b/packages/docs/Lib/fund.md index 09346d680..a4afa9bc0 100644 --- a/packages/docs/Lib/fund.md +++ b/packages/docs/Lib/fund.md @@ -3,10 +3,11 @@ Funds a Bitcoin transaction. ### Type + ```ts ( tx: BitcoinLib.Transaction, - opts?: { + opts?: { include?: string[] exclude?: string[] } @@ -14,33 +15,34 @@ Funds a Bitcoin transaction. ``` ### Syntax + ```js await computer.fund(tx) ``` ### Parameters -#### tx - -A Bitcoin transaction object from the [NakamotoJS](https://github.com/bitcoin-computer/monorepo/tree/main/packages/nakamotojs#nakamotojs-nakamotojs) library. +{.compact} +| Parameter | Description | +|--------------|---------------------------------------------------------------| +| tx | A [Bitcoin transaction](https://github.com/bitcoin-computer/monorepo/blob/main/packages/nakamotojs/ts_src/transaction.ts) object.| #### opts -An optional object can be passed as parameter to ```include``` or ```exclude``` certain UTXOs. When using ``include``, the transaction will be funded with the UTXOs specified as the first inputs. +An optional object can be passed as parameter to `include` or `exclude` certain UTXOs. When using `include`, the transaction will be funded with the UTXOs specified as the first inputs. {.compact} -| Key | Type | Description | Default Value | +| Key | Type | Description | Default Value | |---------|----------|------------------|---------------| -| include | string[] | UTXOs to include | [] | -| exclude | string[] | UTXOs to exclude | [] | - - +| include | string[] | UTXOs to include | [] | +| exclude | string[] | UTXOs to exclude | [] | ### Return value -If the wallet does not have sufficient funds, an error is thrown. +If the wallet does not have sufficient funds, an error is thrown. ### Examples + ```ts // A smart contract class C extends Contract {} @@ -58,4 +60,4 @@ await computer1.fund(tx) // Broadcast the tx const txId = await computer2.broadcast(tx) -``` \ No newline at end of file +``` diff --git a/packages/docs/Lib/load.md b/packages/docs/Lib/load.md index e502fffe8..c452a58e4 100644 --- a/packages/docs/Lib/load.md +++ b/packages/docs/Lib/load.md @@ -3,27 +3,33 @@ Imports a ES6 module from a module specifier encoded as a string \:\. ### Type + ```ts -(rev: string) => Promise +;(rev: string) => Promise ``` ### Syntax + ```js -await computer.load(rev, wallet) +await computer.load(rev) ``` ### Parameters -#### rev -A string encoding a module specifier. +{.compact} +| Parameter | Description | +|--------------|---------------------------------------------------------------| +| rev | A string encoding a module specifier.| ### Return value + A ES6 module. ### Examples + ```ts class A extends Contract {} const rev = await computer.deploy(`export ${A}`) const { A: AA } = await computer.load(rev) expect(AA).to.equal(A) -``` \ No newline at end of file +``` diff --git a/packages/docs/Lib/new.md b/packages/docs/Lib/new.md index 5a962d3ac..87e4b791e 100644 --- a/packages/docs/Lib/new.md +++ b/packages/docs/Lib/new.md @@ -1,31 +1,33 @@ # new -Creates a new smart object. The parameters are a smart contract (a Javascript class inheriting from ``Contract``), a list of arguments for the constructor of the class and an optional module specifier. The arguments of the constructor can be of basic data type or smart objects. The ``new`` function builds a transaction that records the creation of a new smart object, signs it and broadcasts it. Smart objects can be updated by calling their functions, see [here](/tutorial.md#update-a-smart-object). +Creates a new smart object. The parameters are a smart contract (a Javascript class inheriting from `Contract`), a list of arguments for the constructor of the class and an optional module specifier. The arguments of the constructor can be of basic data type or smart objects. The `new` function builds a transaction that records the creation of a new smart object, signs it and broadcasts it. Smart objects can be updated by calling their functions, see [here](/tutorial.md#update-a-smart-object). ### Type + ```ts - any>( +; any>( constructor: T, args?: ConstructorParameters, - mod?: string -) => Promise & MetaData>; + mod?: string, +) => Promise & MetaData> ``` -Here a ``MetaData`` is the type +Here a `MetaData` is the type ```ts -type MetaData = { - _id: string, - _rev: string, - _root: string, - _amount: number, - _owners: string[], - _readers?: string[], - _url?: string +type MetaData = { + _id: string + _rev: string + _root: string + _amount: number + _owners: string[] + _readers?: string[] + _url?: string } ``` ### Syntax + ```js await computer.new(A) await computer.new(A, [10]) @@ -34,20 +36,19 @@ await computer.new(A, ['a'], '9128ab1232...18ba:0') ### Parameters -#### constructor -A named Javascript class that extends from `Contract`. - -#### args -Arguments to the constructor of the class. - -#### mod -A module specifier, i.e., the revision string of a deployed module (see [deploy](/api.md#deploy)). - +{.compact} +| Parameter | Description | +|--------------|---------------------------------------------------------------| +| constructor | A named Javascript class that extends from `Contract`. | +| args | Arguments to the constructor of the class. | +| mod | A module specifier, i.e., the revision string of a deployed module (see [deploy](/api.md#deploy)). ### Return value + Returns an instance of the class `T`. The class `T` should extend from `Contract`. The returned object has extra properties `_id`, `_rev`, `_root`, `_owners`, `_amount` and possibly `_url`, `_readers`. ### Examples + ```ts import { Contract, Computer } from '@bitcoin-computer/lib' @@ -69,4 +70,4 @@ expect(a).to.deep.equal({ _owners: [computer.getPublicKey()], _amount: 5820 }) -``` \ No newline at end of file +``` diff --git a/packages/docs/Lib/rpcCall.md b/packages/docs/Lib/rpcCall.md index b4089f4b9..46f1187c8 100644 --- a/packages/docs/Lib/rpcCall.md +++ b/packages/docs/Lib/rpcCall.md @@ -3,28 +3,31 @@ Calls a Bitcoin RPC method with the given parameters. ### Type + ```ts -(method: string, params: string) => Promise +;(method: string, params: string) => Promise ``` ### Syntax + ```js -await computer.rpcCall(method,params) +await computer.rpcCall(method, params) ``` ### Parameters -#### method -An string encoding the name of the rpc function to be called. - -#### params -An string with the argument list of the rpc function call to be called, separated by spaces. +{.compact} +| Parameter | Description | +|--------------|---------------------------------------------------------------| +| method | An string encoding the name of the rpc function to be called.| +| params | An string with the argument list of the rpc function call to be called, separated by spaces.| ### Return value A JSON object with the result of the rpc method call. ### Examples + ```ts await computer.rpcCall('getBlockchainInfo', '') -``` \ No newline at end of file +``` diff --git a/packages/docs/Lib/send.md b/packages/docs/Lib/send.md index 2a0bdcc8a..2434d8283 100644 --- a/packages/docs/Lib/send.md +++ b/packages/docs/Lib/send.md @@ -3,29 +3,33 @@ Sends a payment. ### Type + ```ts -(amount: number, address: string) => Promise +;(amount: number, address: string) => Promise ``` ### Syntax + ```js await computer.send(satoshis, address) ``` ### Parameters -#### amount -A number representing the amount of satoshis to be sent. - -#### address -An string encoding the receiver address. +{.compact} +| Parameter | Description | +|--------------|---------------------------------------------------------------| +| amount | A number representing the amount of satoshis to be sent.| +| address | An string encoding the receiver address.| ### Return value + If successful, it returns the id of the transaction broadcast. ### Examples + ```ts const satoshis = 100000 const address = '1FFsHfDBEh57BB1nkeuKAk25H44U7mmMXd' const txId = await computer.send(satoshis, address) -``` \ No newline at end of file +``` diff --git a/packages/docs/Lib/sign.md b/packages/docs/Lib/sign.md index 96d6865a3..35ec5b090 100644 --- a/packages/docs/Lib/sign.md +++ b/packages/docs/Lib/sign.md @@ -3,6 +3,7 @@ Signs a Bitcoin transaction. Options can be passed in that determine which inputs to sign, the sigHash type to use, and which script to use. ### Type + ```ts ( tx: BitcoinLib.Transaction, @@ -15,25 +16,27 @@ Signs a Bitcoin transaction. Options can be passed in that determine which input ``` ### Syntax + ```js computer.sign(tx, opts) ``` ### Parameters -#### tx -A Bitcoin transaction, possibly partially signed. +{.compact} +| Parameter | Description | +|--------------|---------------------------------------------------------------| +| tx | A Bitcoin transaction, possibly partially signed.| +| opts | An object with specific parameters to use when signing.| -#### opts -An object with specific parameters to use when signing +The `opts` object can have the following properties: {.compact} -| Key | Type | Description | +| Key | Type | Description | |-------------|--------|---------------------------------------------------------------------------------------------------------------------------------------------------------------| -| inputIndex | number | The input index to be signed | +| inputIndex | number | The input index to be signed | | sighashType | number | A valid sighash type number | -| inputScript | Buffer | A buffer encoding the signature | - +| inputScript | Buffer | A buffer encoding the signature | ### Return value @@ -42,6 +45,7 @@ By default, the `sign` function will make a best effort to sign all inputs, but 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 other inputs. ### Examples + ```ts class C extends Contract {} const tx = await computer.encode({ @@ -50,4 +54,4 @@ const tx = await computer.encode({ }) await computer.fund(tx) computer.sign(tx) -``` \ No newline at end of file +``` diff --git a/packages/docs/Lib/sync.md b/packages/docs/Lib/sync.md index fcd882db7..01c712a87 100644 --- a/packages/docs/Lib/sync.md +++ b/packages/docs/Lib/sync.md @@ -3,30 +3,35 @@ Returns smart objects given a location on the blockchain. The location can either be a revision (a string of the for \:\) or a transaction id. ### Type + ```ts -(location: string) => Promise +;(location: string) => Promise ``` ### Syntax + ```js await computer.sync('0324ba3...ba2') await computer.sync('0324ba3...ba2:0') ``` ### Parameters -#### location -An string encoding a revision or a transaction id. + +{.compact} +| Parameter | Description | +|--------------|---------------------------------------------------------------| +| location | An string encoding a revision or a transaction id.| ### Return value If the function is called with a revision, it returns the smart object stored at the provided revision. Note that the revision must not be a latest revision. In that case a historical state of the revision is returned. -If the function is called with a transaction id, it returns an object of type `{ res: Json; env: Json }`. The value of `res` is the result of evaluating the expression inscribed into the transaction. The `env` object has the same keys as the blockchain environment of the transaction, the values of `env` are the smart objects at these revisions *after* evaluating the expression. +If the function is called with a transaction id, it returns an object of type `{ res: Json; env: Json }`. The value of `res` is the result of evaluating the expression inscribed into the transaction. The `env` object has the same keys as the blockchain environment of the transaction, the values of `env` are the smart objects at these revisions _after_ evaluating the expression. If the parameter is not a valid revision or transaction id, an error is thrown.